Skip to content
Advertisement

Custom Http Status Code in Spring

I am using Spring Boot and I am using Exception Classes thoughout my business logic code. One might look like this:

@ResponseStatus(HttpStatus.BAD_REQUEST)
public class ExternalDependencyException extends RuntimeException {

    public ExternalDependencyException() {
        super("External Dependency Failed");
    }
    public ExternalDependencyException(String message) {
        super(message);
    }

}

Well now there are Exception, where no predefined Http Status code is fitting, so I would like to use a status code like 460 or similar, which is still free, but the annotation ResponseStatus just accepts values from the enum HttpStatus. Is there a way to achieve an Exception class with a custom status code in the java spring boot environment?

Advertisement

Answer

I’m not aware of a way to do this with @ResponseStatus.

One way to solve is this issue is with @RestControllerAdvice. This will allow you to customize how you return your Exception.

@RestControllerAdvice
public class WebRestControllerAdvice  {

    @ExceptionHandler(ExternalDependencyException.class)
    public String handleGitlabException(ExternalDependencyException ex, HttpServletResponse response) {
        try {
            response.sendError(460);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ex.getMessage();
    }
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement