Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using multiple values HttpStatus in @ResponseStatus

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.

like image 759
parbi Avatar asked Feb 25 '23 02:02

parbi


2 Answers

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(..);
    }
}
like image 185
Bozho Avatar answered Mar 12 '23 14:03

Bozho


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.

like image 28
Brandon Yarbrough Avatar answered Mar 12 '23 12:03

Brandon Yarbrough