Spring Boot Rest - How to configure 404 - resource not found Spring Boot Rest - How to configure 404 - resource not found spring spring

Spring Boot Rest - How to configure 404 - resource not found


The solution is pretty easy:

First you need to implement the controller that will handle all error cases. This controller must have @ControllerAdvice -- required to define @ExceptionHandler that apply to all @RequestMappings.

@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");    }}

Provide exception you want to override response in @ExceptionHandler. NoHandlerFoundException is an exception that will be generated when Spring will not be able to delegate request (404 case). You also can specify Throwable to override any exceptions.

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);    }}

Result when I use non defined URL

{    "errorCode": "custom_404",    "errorMessage": "message for 404 error code"}

UPDATE: In case you configure your SpringBoot application using application.properties then you need to add the following properties instead of configuring DispatcherServlet in main method (thanks to @mengchengfeng):

spring.mvc.throw-exception-if-no-handler-found=truespring.web.resources.add-mappings=false


I know this is an old question but here is another way to configure the DispatcherServlet in code but not in the main class. You can use a separate @Configuration class:

@EnableWebMvc@Configurationpublic class ExceptionHandlingConfig {    @Autowired    private DispatcherServlet dispatcherServlet;    @PostConstruct    private void configureDispatcherServlet() {        dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);    }}

Please not that this does not work without the @EnableWebMvc annotation.