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

时间:2017-12-21 09:56:22

标签: spring-mvc spring-aop

    @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方法
  3. 中获取异常发生的控制器类名和包名或类对象

1 个答案:

答案 0 :(得分:1)

这应该有效

@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);
  }