简体   繁体   中英

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. It has a setErrorResult for providing an alternative response if something goes wrong, but no option to supply a http error code.

Surely it must be possible to control the http response code for failed requests.. How do I do that using the new Spring api?

The doc for setErrorResult method says the following:

Set an error value for the DeferredResult and handle it. The value may be an Exception or Throwable in which case it will be processed as if a handler raised the exception.

I suppose by setting an Exception , you may trigger an exception handler that returns the code you desire.

deferredResult.setErrorResult(new Exception());

This will always set the HTTP response code to 500. For finer control HttpServletResponse.setStatus seems to work.

This will work with user411180's client side .

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 . 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)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM