Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/131.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 带有ResponseBy的ExceptionHandler:在方法体中设置ResponseStatus_Java_Spring_Spring Mvc_Exception Handling - Fatal编程技术网

Java 带有ResponseBy的ExceptionHandler:在方法体中设置ResponseStatus

Java 带有ResponseBy的ExceptionHandler:在方法体中设置ResponseStatus,java,spring,spring-mvc,exception-handling,Java,Spring,Spring Mvc,Exception Handling,我有一个方法来处理SpringMVC环境中的一类特殊异常。 metod(简化)实现如下 @ExceptionHandler(AjaxException.class) @ResponseStatus(value=HttpStatus.BAD_REQUEST) @ResponseBody public Exception handleException(AjaxException ex) { return ex; } 这很好,但要返回不同的ResponseStatus,我必须创建一个新的处

我有一个方法来处理SpringMVC环境中的一类特殊异常。 metod(简化)实现如下

@ExceptionHandler(AjaxException.class)
@ResponseStatus(value=HttpStatus.BAD_REQUEST)
@ResponseBody
public Exception handleException(AjaxException ex) {
    return ex;
}
这很好,但要返回不同的
ResponseStatus
,我必须创建一个新的处理方法

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


如果不是,那么更改返回类型是否可能获得相同的结果(可能是我自己序列化异常类并将其作为字符串返回)?

简单,请仔细阅读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异常处理程序。为了解决这个问题,我简单地尝试匹配异常抛出行,一切都正常。

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 APIRROR handleException(RuntimeException e,HttpServletResponse){logger.error(“异常发生{}”,e.getMessage(),e);response.setStatus(HttpStatus.BAD_REQUEST.value());返回新的APIRROR(HttpStatus.BAD_请求,例如getMessage();}