I am using the Spring annotation @ResponseStatus
in my Exception like
@ResponseStatus(value=HttpStatus.UNAUTHORIZED)
public class UnauthorizedException extends Exception{
}
Problem is I want to throw the same error for a number of values like HttpStatus.SC_SERVICE_UNAVAILABLE
, etc..
Is there any way to use multiple values in @ResponseStatus
? Thanks in advance.
No. You can't have multiple http status codes. Check http spec
If you actually want to set different status codes in different scenarios (but only one status code per response), then remove the annotation, and add it via code:
public X method(HttpServletResponse response) {
if (..) {
response.setStatus(..);
} else {
response.setStatus(..);
}
}
The only workaround that comes to mind is not using the @ResponseStatus
annotation. Consider writing your own error handling code in the controller that catches the relevant exception sets the error code in the way you would prefer for that class. If it's in several controllers, consider writing an interceptor or using AOP.
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