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?
Spring provides a few primary ways to return custom status codes from its Controller classes: using a ResponseEntity. using the @ResponseStatus annotation on exception classes, and. using the @ControllerAdvice and @ExceptionHandler annotations.
Sending Specific Response Status Codes The very basic way of sending response status is to use ResponseEntity object, which is returned by a controller. Controller can set a specific response status in the Response. Alternatively, we can use @ResponseStatus annotation to specify the desired status code.
Annotation Type ResponseStatusMarks a method or exception class with the status code() and reason() that should be returned. The status code is applied to the HTTP response when the handler method is invoked and overrides status information set by other means, like ResponseEntity or "redirect:" .
DeferredResult provides an alternative to using a Callable for asynchronous request processing. While a Callable is executed concurrently on behalf of the application, with a DeferredResult the application can produce the result from a thread of its choice.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With