Skip to content

Resolve optional HandlerMethod parameter of @ExceptionHandler method to null #35067

@cbsingh1

Description

@cbsingh1

Summary
I have a Spring Boot service where custom JSON error responses are returned when controller methods are annotated with a custom annotation.

When accessing an endpoint that does not exist, the default Spring 404 JSON body is returned, but the following unexpected error detail appears in the response:

java.lang.IllegalStateException: Could not resolve parameter [1] in handleException(java.lang.Exception,org.springframework.web.method.HandlerMethod) throws java.lang.Exception: No suitable resolver	at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:224) 

How to Reproduce:
You can reproduce this by running the test here:
https://github.com/cbsingh1/exception-handler-method/blob/main/src/test/java/com/example/exception_handler/ExceptionHandlerApplicationTests.java

Expected Behavior
If the HandlerMethod cannot be resolved (e.g., because no handler exists for the request), I would expect:

  • handlerMethod to be null, allowing me to handle it explicitly in my exception handler.
  • or cleaner logging/formatting of the error
@ExceptionHandler(Exception.class) ResponseEntity<String> handleAllExceptions(Exception exception, HandlerMethod handlerMethod) throws Exception { if (handlerMethod == null) { // special handling } if (handlerMethod.hasMethodAnnotation(MyCustomAnnotation.class)) { return ResponseEntity.internalServerError().body("custom failure message"); } throw exception; } 

Suggestion
It would be great if Spring could:

  • Provide a null (or safe default) for HandlerMethod when no handler is resolved.
  • Improve error formatting

Metadata

Metadata

Assignees

Labels

in: webIssues in web modules (web, webmvc, webflux, websocket)type: enhancementA general enhancement

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions