[英]Spring 3.2 DeferredResult - How to set status code for error response?
Spring Web 3.2 comes with a DeferredResult
class for asynchronous request processing. Spring Web 3.2附带了一个用于异步请求处理的
DeferredResult
类。 It has a setErrorResult
for providing an alternative response if something goes wrong, but no option to supply a http error code. 它有一个
setErrorResult
用于在出现问题时提供备用响应,但没有提供http错误代码的选项。
Surely it must be possible to control the http response code for failed requests.. How do I do that using the new Spring api? 当然必须能够控制失败请求的http响应代码。如何使用新的Spring api做到这一点?
The doc for setErrorResult
method says the following: setErrorResult
方法的doc说明如下:
Set an error value for the DeferredResult and handle it.
为DeferredResult设置错误值并处理它。 The value may be an Exception or Throwable in which case it will be processed as if a handler raised the exception.
该值可以是Exception或Throwable,在这种情况下,它将被处理,就像处理程序引发异常一样。
I suppose by setting an Exception
, you may trigger an exception handler that returns the code you desire. 我想通过设置
Exception
,您可以触发一个返回所需代码的异常处理程序。
deferredResult.setErrorResult(new Exception());
This will always set the HTTP response code to 500. For finer control HttpServletResponse.setStatus seems to work. 这将始终将HTTP响应代码设置为500.为了更好的控制,HttpServletResponse.setStatus似乎可以工作。
This will work with user411180's client side . 这将适用于user411180的客户端 。
public DeferredResult<List<Point>> getMessages(@RequestParam int reqestedIndex,
final HttpServletResponse response) {
final DeferredResult<List<Point>> deferredResult = new DeferredResult<>();
deferredResult.onCompletion(...);
deferredResult.onTimeout(new Runnable() {
@Override
public void run() {
deferredResult.setErrorResult("Explanation goes here.");
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); //or SC_NO_CONTENT
}
});
longPollRequests.put(deferredResult, reqestedIndex);
return deferredResult;
}
The exception that you pass as the argument to setErrorResult
can be annotated with @ResponseStatus
. 您作为参数传递给
setErrorResult
的异常可以使用@ResponseStatus
进行注释。 eg create an exception class of your own: 例如,创建自己的异常类:
@ResponseStatus(HttpStatus.NOT_FOUND)
class NotFoundException extends RuntimeException {
// add your own constructors to set the error message
// and/or cause. See RuntimeException for valid ctors
}
Then in your code use it with the constructor you have created, for example:
deferredResult.setErrorResult(new NotFoundException(reason, cause));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.