如何在Spring @ExceptionHandler中将异常作为@ResponseStatus注释的异常抛出?
问题内容:
我有一个例外,当我想要404页面时总是抛出:
@ResponseStatus( value = HttpStatus.NOT_FOUND )
public class PageNotFoundException extends RuntimeException {
我想创建整个控制器范围@ExceptionHandler
,并将其重新抛出ArticleNotFoundException
(导致错误500)作为我的404异常:
@ExceptionHandler( value=ArticleNotFoundException.class )
public void handleArticleNotFound() {
throw new PageNotFoundException();
}
但这不起作用-我仍然有 错误500 和Spring日志:
ExceptionHandlerExceptionResolver - Failed to invoke @ExceptionHandler method: ...
请注意,我将代码翻译为html,因此response不能为空或类似的简单String ResponseEntity
。web.xml
条目:
<error-page>
<location>/resources/error-pages/404.html</location>
<error-code>404</error-code>
</error-page>
最终评论的答案
这不是完全重新抛出,但是至少它使用了web.xml
像我这样的错误页面映射PageNotFoundException
@ExceptionHandler( value = ArticleNotFoundException.class )
public void handle( HttpServletResponse response) throws IOException {
response.sendError( HttpServletResponse.SC_NOT_FOUND );
}
问题答案:
不要抛出异常,请尝试以下操作:
@ExceptionHandler( value=ArticleNotFoundException.class )
public ResponseEntity<String> handleArticleNotFound() {
return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
}
这基本上将返回一个Spring对象,该对象将由您的控制器转换为404。
如果要将不同的HTTP状态消息返回到前端,可以将其传递给其他HttpStatus。
如果您对使用注解不满意,只需使用@ResponseStatus注释该控制器方法,不要抛出异常。
基本上,如果您使用@ExceptionHandler
90%的方式注释方法,则Spring希望该方法使用该异常而不抛出另一个异常。通过抛出一个不同的异常,Spring认为未处理该异常并且您的异常处理程序失败,因此日志中的消息
编辑:
要使其返回特定页面,请尝试
return new ResponseEntity<String>(location/of/your/page.html, HttpStatus.NOT_FOUND);
编辑2:您应该能够做到这一点:
@ExceptionHandler( value=ArticleNotFoundException.class )
public ResponseEntity<String> handleArticleNotFound(HttpServletResponse response) {
response.sendRedirect(location/of/your/page);
return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
}