Spring 3.2 DeferredResult - How to set status code for error response?

Spring Web 3.2 ships with the DeferredResult class to handle asynchronous requests. It has setErrorResult to provide an alternative answer if something goes wrong, but there is no way to provide an http error code.

Of course, it should be possible to manage the HTTP response code for failed requests. How to do this using the new Spring api?

+7
source share
3 answers

The doc for the setErrorResult method says the following:

Set the error value to DeferredResult and process it. The value can be an Exception or Throwable, in which case it will be processed as if the handler raised the exception.

I suppose by setting Exception you can call an exception handler that returns the desired code.

+7
source
 deferredResult.setErrorResult(new Exception()); 

This will always indicate an HTTP response code of 500. For more precise control, HttpServletResponse.setStatus works.

This will work with the 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; } 
+2
source

The exception that you pass as the argument to setErrorResult can be annotated with @ResponseStatus . For example, create your own exception class:

  @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 created, for example:
  deferredResult.setErrorResult(new NotFoundException(reason, cause)); 
0
source

All Articles