【问题标题】:How to rethrow exception as @ResponseStatus-annotated exception in Spring @ExceptionHandler?如何在Spring @ExceptionHandler中将异常重新抛出为@ResponseStatus注释的异常?
【发布时间】:2014-05-29 10:40:30
【问题描述】:

我已经例外,当我想要一个 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,因此响应不能为空或像 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 );

    }

【问题讨论】:

    标签: java spring exception spring-mvc exception-handling


    【解决方案1】:

    不要抛出异常,试试这个:

    @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);
    }
    

    【讨论】:

    • 已投赞成票,但这可用作404 代码,但发送空响应。这与我的 PageNotFoundException 的行为不同 - 由 web.xml &lt;error-page&gt; 转换为 .html 文件
    • 不幸的是,它将该路径字符串作为响应正文,只是将其显示在页面上。
    • 它适用于返回带有路径的String 并由`@ResponseStatus(value=HttpStatus.NOT_FOUND)` 注释,但形式上,这不是对我的问题的完全回应——没有重新抛出但简单的重复的、分散的代码。我会再等,如果没有人回复,我会接受并更新通知。
    • 不用担心,两周前我正在和自己非常相似的东西搏斗。祝你好运
    • 刚找到这个,读一读。这将允许您使用 @ExceptionHandler 并重定向到您的错误页面。 stackoverflow.com/questions/15318583/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-02
    • 2011-02-21
    • 2021-10-08
    • 2016-09-16
    • 2012-06-29
    • 2015-10-28
    • 2011-06-27
    相关资源
    最近更新 更多