spring-framework icon indicating copy to clipboard operation
spring-framework copied to clipboard

Simplify handling of 404 errors

Open rstoyanchev opened this issue 3 years ago • 0 comments

DispatcherServlet calls sendError(404) by default in case of no matching handler, or raises NoHandlerFoundException when its property throwExceptionIfNoHandlerFound is enabled, allowing applications to handle it, which is important for REST APIs.

This works, but not out of the box, and leads to confusion such as in https://github.com/spring-projects/spring-boot/issues/3980. Even though there is a Boot property, the property must be discovered and turned on for no apparent reason or benefit. Originally, the concern may have been the exception could remain unhandled, but these days we can assume DefaultHandlerExceptionResolver is in place which leads to the same outcome, sendError(404), while it also allows custom handling via @ExceptionHandler, as well as an RFC 7807 response via ResponseEntityExceptionHandler, out of the box.

To add to this, ResourceHttpRequestHandler was never updated along the same lines, and still does sendError(404), so with static resources mapped to /**, the handler becomes a catch-all for 404 errors, and leads to more confusion since the property now has no effect, see https://github.com/spring-projects/spring-boot/issues/7653, and there is no fix for it.

We should change ResourceHttpRequestHandler to raise NoHandlerFoundException in order to allow consistent handling of 404 errors. This should not make a difference out of the box since DefaultHandlerExceptionResolver will handle it in to the same effect, and where there is an @ExceptionHandler, that's still intentional handling, consistent with other exceptions.

We should also change DispatcherServlet to raise NoHandlerFoundException by default, and deprecate the property. There should be no reason why NoHandlerFoundException isn't always raised, instead of being short-circuited by going directly to sendError(404) and not allowing any other way to handle it.

rstoyanchev avatar Nov 15 '22 12:11 rstoyanchev