Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot - taking control of 404 Not Found

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?

like image 980
damiend Avatar asked May 19 '15 15:05

damiend


People also ask

Why does spring boot say 404 error?

We went through the two most common reasons for receiving a 404 response from our Spring application. The first was using an incorrect URI while making the request. The second was mapping the DispatcherServlet to the wrong url-pattern in web.

How do I get rid of WhiteLabel error page?

Another way of disabling the WhiteLabel Error is excluding the ErrorMvcAutoConfiguration . Alternatively, the exclusion can be done in an annotation. When the WhiteLabel Error Page is disabled and no custom error page is provided, the web server's error page (Tomcat, Jetty) is shown.


1 Answers

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, the 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 to the following code:

@SpringBootApplication
@EnableWebMvc
public class Application {  
    @Autowired
    private DispatcherServlet servlet;

    public static void main(String[] args) throws FileNotFoundException, IOException {
        SpringApplication.run(Application.class, args);
    }
    
    @Bean
    public CommandLineRunner getCommandLineRunner(ApplicationContext context) {
        servlet.setThrowExceptionIfNoHandlerFound(true);
        return args -> {};
    }
}

After this you can handle NoHandlerException in your @RestControllerAdvice class

@RestControllerAdvice
public class AppException {

    @ExceptionHandler(value={NoHandlerFoundException.class})
    @ResponseStatus(code=HttpStatus.BAD_REQUEST)
    public ApiError badRequest(Exception e, HttpServletRequest request, HttpServletResponse response) {
        e.printStackTrace();
        return new ApiError(400, HttpStatus.BAD_REQUEST.getReasonPhrase());
    }
}   

I have created ApiError class to return customized error response

public class ApiError {
    private int code;
    private String message;
    public ApiError(int code, String message) {
        this.code = code;
        this.message = message;
    }
    public ApiError() {
    }   
    //getter & setter methods...
}
like image 177
vel Avatar answered Sep 22 '22 13:09

vel