Kin*_*cka 9 java spring exception-handling exception spring-mvc
我已经例外了,当我想要一个404页面时,我总是扔掉它:
@ResponseStatus( value = HttpStatus.NOT_FOUND )
public class PageNotFoundException extends RuntimeException {
Run Code Online (Sandbox Code Playgroud)
我想创建控制器范围@ExceptionHandler,将重新掷ArticleNotFoundException(这会导致错误500)作为我的404例外:
@ExceptionHandler( value=ArticleNotFoundException.class )
public void handleArticleNotFound() {
throw new PageNotFoundException();
}
Run Code Online (Sandbox Code Playgroud)
但它不起作用 - 我仍然有错误500和Spring日志:
ExceptionHandlerExceptionResolver - Failed to invoke @ExceptionHandler method: ...
请注意,我将代码翻译为html,因此响应不能为空或简单的字符串ResponseEntity.web.xml条目:
<error-page>
<location>/resources/error-pages/404.html</location>
<error-code>404</error-code>
</error-page>
Run Code Online (Sandbox Code Playgroud)
最终的解决方案回答者:评论
这不是一个全面的重新抛出,但至少它使用web.xml错误页面映射喜欢我PageNotFoundException
@ExceptionHandler( value = ArticleNotFoundException.class )
public void handle( HttpServletResponse response) throws IOException {
response.sendError( HttpServletResponse.SC_NOT_FOUND );
}
Run Code Online (Sandbox Code Playgroud)
Jam*_*ENL 10
而不是抛出异常试试这个:
@ExceptionHandler( value=ArticleNotFoundException.class )
public ResponseEntity<String> handleArticleNotFound() {
return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
}
Run Code Online (Sandbox Code Playgroud)
这基本上会返回一个Spring对象,由控制器转换为404.
如果要将不同的HTTP状态消息返回到前端,可以将其传递给不同的HttpStatus.
如果您在使用注释这样deadset,只是标注与@ResponseStatus该控制器的方法,并且不抛出异常.
基本上如果你注释一个方法,@ExceptionHandler我90%确定Spring期望该方法消耗该异常而不抛出另一个异常.通过抛出不同的异常,春认为,异常没有被处理,你的异常处理程序在日志中失败,因此消息
编辑:
为了得到它返回一个特定页面的尝试
return new ResponseEntity<String>(location/of/your/page.html, HttpStatus.NOT_FOUND);
Run Code Online (Sandbox Code Playgroud)
编辑2:你应该能够做到这一点:
@ExceptionHandler( value=ArticleNotFoundException.class )
public ResponseEntity<String> handleArticleNotFound(HttpServletResponse response) {
response.sendRedirect(location/of/your/page);
return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6561 次 |
| 最近记录: |