Description
This issue occurs in Spring Boot 1.1.12, 1.2.0, and 1.2.5. There are a few related answers on StackOverflow but none of them seem to work.
I'm trying to override the error handling behaviour to return a json-encoded custom POJO to the user when exceptions are thrown by the controllers in my application. This works for most exceptions but I can't get it to work with for 404s where there is no handler matching the path of the request.
Overriding the DispatcherServlet
and setting setThrowExceptionIfNoHandlerFound
to true
does not result in the appropriate exception handler being called.
Here is my DispatcherServlet
Bean declaration:
@Configuration
public class WebAppContext extends WebMvcConfigurerAdapter {
@Bean(name = DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)
public DispatcherServlet dispatcherServlet() {
DispatcherServlet ds = new DispatcherServlet();
ds.setDetectAllHandlerAdapters(true);
ds.setDetectAllHandlerExceptionResolvers(true);
ds.setDetectAllHandlerMappings(true);
ds.setDetectAllViewResolvers(true);
ds.setThrowExceptionIfNoHandlerFound(true);
return ds;
}
// ... more Bean definitions
}
And here's part of the global Exception handler:
@ControllerAdvice(annotations = RestController.class)
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
// TODO: figure out how to configure the DispatcherServlet's throwExceptionIfNoHandlerFound property so that this can work
@Override
protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
return new ResponseEntity<>(new CustomErrorType(HttpStatus.NOT_FOUND.value(), "Not Found"), HttpStatus.NOT_FOUND);
}
// ... @ExceptionHandler methods etc.
}
I have also tried using the BeanPostProcessor
interface to customise the DispatcherServlet
as noted in a comment on an answer to this question, but that doesn't work either.
The documentation for how to handle global exceptions and customise the DispatcherServlet
is incredibly obtuse. Am I missing something or is there a bug in there somewhere?