Spring boot 404 error custom error response ReST
For those Spring Boot 2 users who don't wanna use @EnableWebMvc
application.properties
server.error.whitelabel.enabled=falsespring.mvc.throw-exception-if-no-handler-found=truespring.resources.add-mappings=false
ControllerAdvice
@RestControllerAdvicepublic class ExceptionResolver { @ExceptionHandler(NoHandlerFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) public HashMap<String, String> handleNoHandlerFound(NoHandlerFoundException e, WebRequest request) { HashMap<String, String> response = new HashMap<>(); response.put("status", "fail"); response.put("message", e.getLocalizedMessage()); return response; }}
I've provided the sample solution on how to override response for 404 case. The solution is pretty much simple and I am posting sample code but you can find more details on the original thread: Spring Boot Rest - How to configure 404 - resource not found
First: define Controller that will process error cases and override response:
@ControllerAdvicepublic class ExceptionHandlerController { @ExceptionHandler(NoHandlerFoundException.class) @ResponseStatus(value= HttpStatus.NOT_FOUND) @ResponseBody public ErrorResponse requestHandlingNoHandlerFound() { return new ErrorResponse("custom_404", "message for 404 error code"); }}
Second: you need to tell Spring to throw exception in case of 404 (could not resolve handler):
@SpringBootApplication@EnableWebMvcpublic class Application { public static void main(String[] args) { ApplicationContext ctx = SpringApplication.run(Application.class, args); DispatcherServlet dispatcherServlet = (DispatcherServlet)ctx.getBean("dispatcherServlet"); dispatcherServlet.setThrowExceptionIfNoHandlerFound(true); }}
404 error is handled by DispatcherServlet. there is a property throwExceptionIfNoHandlerFound, which you can override.
In Application class you can create a new bean:
@BeanDispatcherServlet dispatcherServlet () { DispatcherServlet ds = new DispatcherServlet(); ds.setThrowExceptionIfNoHandlerFound(true); return ds;}
...and then catch the NoHandlerFoundException exception in
@EnableWebMvc@ControllerAdvicepublic class GlobalControllerExceptionHandler { @ExceptionHandler @ResponseStatus(value=HttpStatus.NOT_FOUND) @ResponseBody public ErrorMessageResponse requestHandlingNoHandlerFound(final NoHandlerFoundException ex) { doSomething(LOG.debug("text to log")); }}