Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring REST @ResponseStatus with Custom exception class does not change the return Status code

Tags:

spring-rest

I have a exception class like follows

@ResponseStatus(value=HttpStatus.UNPROCESSABLE_ENTITY, reason="Unprocessable Entity")  // 422
public class UnprocessableEntityException extends RuntimeException {
}

Now the status is not returned as 422 unless I write a specific handler in the Controller class like :

@ExceptionHandler(UnprocessableEntityException.class)
    @ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)
    public String handleException(Exception ex) {
...
}

As I understand I should not need @ExceptionHandler in first place, not sure what am I missing.

like image 244
explorer Avatar asked Dec 03 '15 19:12

explorer


People also ask

How do I change the response code on a spring rest controller?

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.

How do I change the response status in spring boot?

If we want to specify the response status of a controller method, we need to annotate that method with the @ResponseStatus annotation. It has two interchangeable arguments for the desired response type: code and value. Note, that when we set reason, Spring calls HttpServletResponse. sendError().

Which of the following annotation is used for returning Httpstatus code?

The @ResponseStatus annotation can be used on any method that returns back a response to the client.

How does @ResponseStatus work?

We can use @ResponseStatus to mark a method or an exception class with a status code and reason that should be returned. On invoking the marked handler method or when a specified exception is thrown, the HTTP status will be set to the one defined using @ResponseStatus annotation.


1 Answers

Throwing a @ResponseStatus annotated exception from a controller method should be enough for the framework to write the HTTP status code - no @ExceptionHandler necessary.

The following will write a 422 Status on hitting the webapp root as expected:

@Controller
public class ExceptionController {

    @RequestMapping("/")
    public void action() {
        throw new ActionException();
    }

    @ResponseStatus(value = HttpStatus.UNPROCESSABLE_ENTITY, reason = "nope")
    public static class ActionException extends RuntimeException {}
}

This works courtesy of the ResponseStatusExceptionResolver which is created by Spring MVC by default - if it's not working for you, my guess is that this default exception resolver has been removed (by e.g. overriding WebMvcConfigurationSupport.configureHandlerExceptionResolvers or otherwise configuring your context's HandlerExceptionResolvers so that the ResponseStatusExceptionResolver is trumped.)

like image 127
ryanp Avatar answered Sep 27 '22 19:09

ryanp