5
    @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
Ashok Kumar N
  • 573
  • 6
  • 23
  • checkout my answer here. https://stackoverflow.com/questions/47882476/how-to-retrieve-attribute-from-controlleradvice-selector-in-controlleradvice-cla/47885256#47885256 – pvpkiran Dec 21 '17 at 09:58
  • @pvpkiran thanks for the suggestion but without custom annotation i need a alternate answer so that i dont want to refactor all the controllers . i can able to change the advised controller not any other else – Ashok Kumar N Dec 21 '17 at 10:09
  • I have added the answer below. It is pretty much same. only difference is argument in `@ControlelrAdvice` is removed. Now it matches any controllers instead of controllers with custom annotations. – pvpkiran Dec 21 '17 at 10:14

1 Answers1

9

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);
  }
pvpkiran
  • 25,582
  • 8
  • 87
  • 134
  • 1
    Intentionally calling `GET` resource with `PUT` method to validate `HttpRequestMethodNotSupportedException` and defined the controoler `@ExceptionHandler public ResponseEntity> handle(HttpRequestMethodNotSupportedException exception, ServletWebRequest req, HandlerMethod handlerMethod) {}` and facing the error : Could not resolve method parameter at index 2 - No suitable resolver for argument 2 of type 'org.springframework.web.method.HandlerMethod` Is there anything I am missing? – Paramesh Korrakuti Sep 14 '18 at 00:22
  • This gives class info. Can we get method name ? – PAA Jan 23 '20 at 16:37
  • I think you can. `handlerMethod.getMethod().toString()` – pvpkiran Jan 23 '20 at 16:57