There is a server built on Spring + Hibernate. It is necessary to catch the error 404 when the user knocks on the wrong address (for example, localhost: 8080 / tes instead of test). For this, I wrote GlobalExceptionHandlerController.class . It perfectly catches all errors except 404. What is the problem?

 @ControllerAdvice public class GlobalExceptionHandlerController { @ResponseStatus(value = HttpStatus.NOT_FOUND) @ExceptionHandler(value = NullPointerException.class) @ResponseBody public String handleNullPointerException(Exception e) { System.out.println("A null pointer exception ocurred " + e); return "nullpointerExceptionPage"; } @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) @ExceptionHandler(value = Exception.class) @ResponseBody public String handleAllException(Exception e) { System.out.println("A unknow Exception Ocurred: " + e); return "unknowExceptionPage"; } @ExceptionHandler(NoHandlerFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) @ResponseBody public String handleResourceNotFoundException() { return "notFoundJSPPage"; } } 
  • one
    The fact is that 404 error is not an exception, so do not get caught. You need to write a filter to catch 404. - Roman C

1 answer 1

A client can get HTTP 404 for 2 reasons: when accessing an erroneous url address ( localhost:8080/tes instead of localhost:8080/test ) or when accessing a nonexistent resource ( localhost:8080/test/42 , and an object with key 42 does not exist).

In fact, from the point of view of the http protocol, this is all the same mistake - accessing a non-existent resource, and the separation is done in order to show differences in the processing of both situations.

In the 1st case, when accessing by the erroneous url-address, the error 404 will be returned by Spring (since no corresponding mapping will be found for the url-address). To specify the page returned in this case, you must specify it in the config file. When configured with xml, it will be something like this:

 </web-app> ... <error-page> <error-code>404</error-code> <location>/WEB-INF/pages/404.jsp</location> </error-page> </web-app> 

In the 2nd case, for example, when accessing localhost:8080/test/42 , the corresponding controller method is called and inside it you understand that the object with the key 42 does not exist. You throw some kind of your own exception, for example, called ResourceNotFoundException , and in ControllerAdvice add processing of this exception, where you will redirect to the necessary page.