【问题标题】:ExceptionHandler with ResponseBody: set ResponseStatus in method body带有 ResponseBody 的 ExceptionHandler:在方法主体中设置 ResponseStatus
【发布时间】:2013-09-02 14:42:18
【问题描述】:

我有一种方法可以在 Spring MVC 环境中处理特定类别的异常。 方法(简化)实现如下

@ExceptionHandler(AjaxException.class)
@ResponseStatus(value=HttpStatus.BAD_REQUEST)
@ResponseBody
public Exception handleException(AjaxException ex) {
    return ex;
}

这很好用,但要返回不同的ResponseStatus,我必须创建一个新的处理方法。

是否可以在不改变返回类型的情况下,改变方法体内的响应状态,而不是使用@ResponseStatus注解?

如果不是,是否可以通过改变返回类型来达到同样的结果(可能是自己序列化异常类,然后作为字符串返回)?

【问题讨论】:

    标签: java spring spring-mvc exception-handling


    【解决方案1】:

    HttpServletResponse 添加到方法签名中,然后调用setStatus 方法。

    @ExceptionHandler(AjaxException.class)
    @ResponseBody
    public Exception handleException(AjaxException ex, HttpServletResponse response) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return ex;
    }
    

    类似的东西应该可以工作。

    【讨论】:

    • 正确!我自己找到了这个解决方案,但应用程序一直运行错误......问题出在其他地方
    • 它对我不起作用:@ExceptionHandler(RuntimeException.class) public ApiError handleException(RuntimeException e, HttpServletResponse response) { logger.error("发生异常{}", e.获取消息(),e); response.setStatus(HttpStatus.BAD_REQUEST.value());返回新的 ApiError(HttpStatus.BAD_REQUEST, e.getMessage()); }
    【解决方案2】:

    很简单,请仔细阅读 spring 文档。

    可以将HttpServletResponse 作为对象参数传递。在这样的对象中可以设置返回码。语法如下:

    @ExceptionHandler(AjaxException.class)
    @ResponseBody
    public AjaxException handleException(AjaxException ex,HttpServletResponse response) {
                //test code ahead, not part of the solution
    
                //throw new NullPointerException();
    
                //end of test code
    
    
        response.setStatus(404);//example
        return  ex;
    }
    

    这将返回异常的 json 序列化以及指定的 http 返回码。

    编辑: 我昨天删除了这个答案,因为这个解决方案似乎不起作用。问题有点棘手:当您以这种方式管理异常时,如果使用 ExceptionHandler 注释的方法本身抛出异常,则抛出的异常将被忽略,而是抛出原始异常。

    我的代码有点像我发布的解决方案(它在方法的开头抛出了异常),所以我看不到 json 输出,而是触发了标准的 spring 异常处理程序。为了解决这个问题,我只是尝试捕获异常抛出线,一切都很好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-10
      • 1970-01-01
      • 2011-07-03
      • 1970-01-01
      • 2011-07-04
      • 2015-01-14
      • 2013-07-04
      相关资源
      最近更新 更多