I have made exception, that I'm throwing always when I want a 404 page:
@ResponseStatus( value = HttpStatus.NOT_FOUND )
public class PageNotFoundException extends RuntimeException {
I want to create controller-wide @ExceptionHandler
that will re-throw ArticleNotFoundException
(which causes error 500) as my 404 exception:
@ExceptionHandler( value=ArticleNotFoundException.class )
public void handleArticleNotFound() {
throw new PageNotFoundException();
}
But it doesn't work - I still have error 500 and Spring logs:
ExceptionHandlerExceptionResolver - Failed to invoke @ExceptionHandler method: ...
Note that I translate code to html so response cannot be empty or simple String like with ResponseEntity
. web.xml
entry:
<error-page>
<location>/resources/error-pages/404.html</location>
<error-code>404</error-code>
</error-page>
FINAL SOLUTION FROM ANSWER COMMENTS
It's not a full re-throw, but at least it uses web.xml
error page mapping like my PageNotFoundException
@ExceptionHandler( value = ArticleNotFoundException.class )
public void handle( HttpServletResponse response) throws IOException {
response.sendError( HttpServletResponse.SC_NOT_FOUND );
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…