代码之家  ›  专栏  ›  技术社区  ›  Ashok Kumar N

如何在Spring MVC中的@controllerAdvice或@RestControllerAdvice中找到控制器名称?

  •  4
  • Ashok Kumar N  · 技术社区  · 7 年前
        @ControllerAdvice
        public class GlobalExceptionHandler {
    
            @ExceptionHandler(NoHandlerFoundException.class)
            public ResponseEntity<Error> handle(NoHandlerFoundException ex){
                String message = "HTTP " + ex.getHttpMethod() + " for " + ex.getRequestURL() + " is not supported.";
                Error error = new Error(HttpStatus.NOT_FOUND.value(), message);
                return new ResponseEntity<Error>(error, HttpStatus.NOT_FOUND);
            }
    
        }
    
    1. 我正在将@ControllerAdvice与@ExceptionHandler一起使用。
    2. 我需要获取handle方法中发生异常的控制器类名和包名或类对象
    1 回复  |  直到 6 年前
        1
  •  6
  •   pvpkiran    7 年前

    这应该行得通

    @ControllerAdvice
    class AdviceA {
    
      @ExceptionHandler({SomeException.class})
      public ResponseEntity<String> handleSomeException(SomeException pe, HandlerMethod handlerMethod) {
        Class controllerClass = handlerMethod.getMethod().getDeclaringClass();
        //controllerClass.toString will give you fully qualified name
        return new ResponseEntity<>("SomeString", HttpStatus.BAD_REQUEST);
      }