I'm trying to figure out the simplest way to take control over the 404 Not Found handler of a basic Spring Boot RESTful service such as the example provided by Spring:
https://spring.io/guides/gs/rest-service/
Rather than have it return the default Json output:
{
"timestamp":1432047177086,
"status":404,
"error":"Not Found",
"exception":"org.springframework.web.servlet.NoHandlerFoundException",
"message":"No handler found for GET /aaa, ..."
}
I'd like to provide my own Json output.
By taking control of the DispatcherServlet
and using DispatcherServlet#setThrowExceptionIfNoHandlerFound(true)
, I was able to make it throw an exception in case of a 404 but I can't handle that exception through a @ExceptionHandler
, like I would for a MissingServletRequestParameterException
. Any idea why?
Or is there a better approach than having a NoHandlerFoundException thrown and handled?
The
@EnableWebMvc
based solution can work, but it might break Spring boot auto configurations. The solution I am using is to implementErrorController
:According to the Spring documentation appendix A. there is a boolean property called
spring.mvc.throw-exception-if-no-handler-found
which can be used to enable throwingNoHandlerFoundException
. Then you can create exception handler like any other.@ExceptionHandler
itself without@ControllerAdvice
(or@RestControllerAdvice
) can't be used, because it's bound to its controller only.It works perfectly Fine.
When you are using SpringBoot it does not handle (404 Not Found) explicitly it uses WebMvc error response. If your Spring Boot should handle that exception then you should do some hack around Spring Boot. For 404 Exception class is NoHandlerFoundException if you want to handle that exception in your @RestControllerAdvice Class you must add @EnableWebMvc annotation in your Application class and set setThrowExceptionIfNoHandlerFound(true); in DispatcherServlet. Please Refer the code
After this you can handle NoHandlerException in your @RestControllerAdvice class
I have created ApiError class to return customized error response
In short, the
NoHandlerFoundException
is thrown from the Container, not from your application within your container. Therefore your Container has no way of knowing about your@ExceptionHandler
as that is a Spring feature, not anything from the container.What you want is a
HandlerExceptionResolver
. I had the very same issue as you, have a look at my solution over there: How to intercept "global" 404s on embedded Tomcats in spring-boot