How to find controller name in @controllerAdvice or @RestControllerAdvice in Spring MVC?

对着背影说爱祢 提交于 2020-04-10 05:40:07

问题


    @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. I am using @ControllerAdvice with @ExceptionHandler.
  2. I need to get the exception occurred controller class name and package name or class object inside the handle method

回答1:


This should work

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


来源:https://stackoverflow.com/questions/47922306/how-to-find-controller-name-in-controlleradvice-or-restcontrolleradvice-in-spr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!