Reputation: 553
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.
Upvotes: 6
Views: 9305
Reputation: 682
Why not just create multiple exception classes and throw the appropriate one?
Upvotes: 0
Reputation: 597124
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(..);
}
}
Upvotes: 4
Reputation: 38389
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.
Upvotes: 3
Reputation: 579
You can set the response code in the HttpServletResponse
class with the .setStatus()
method, that you could get from the applicationContext
.
Upvotes: 1