Better approach to return HttpStatus code Spring REST
Returning ResponseEntity
as @M-deinum wrote is definitely way to go. Additionally, instead of defining behavior for each exception in @ControllerAdvice
you can just annotate your exceptions classes with appropriate @ResponseStatus
annotations.
@ResponseStatus(HttpStatus.BAD_REQUEST)
class SomeException extends RuntimeException {
}
azalut
Updated on June 27, 2022Comments
-
azalut almost 2 years
I develope rest service using spring for a long time, and till now my approach to return http status code was like this:
@RequestMapping(value = "/sth") public void name(HttpServletResponse response){ boolean lever = service.doSomethingAndReturnTrueIfSucceedOrFalseIfNot(); if(lever){ response.setStatus(HttpServletResponse.SC_OK); }else{ response.setStatus(HttpServletResponse.SC_BAD_REQUEST); //NOT_FOUND or whatever } }
But I am sure there is a better way to do this. I know that we have @ResponseStatus annotation, but it is.. static, I mean it returns always the same code - but what if something would have gone wrong? Then I dont want for example, to have 200 OK as response code.
I found the solution like this: add @ResponseStatus as static response code, but when something goes wrong in the controller, then throw some custom exception and catch it in new @ControllerAdvice class, and there also add @ResponseStatus annotation and return proper code.
@RequestMapping(value = "/sth") @ResponseStatus(HttpStatus.OK) public void name(HttpServletResponse response) throws Exception{ boolean lever = service.doSomethingAndReturnTrueIfSucceedOrFalseIfNot(); if(!lever){ throw new SomethingWentWrongCustomException("Not okay.."); } }
And then catch it in the class like:
@ControllerAdvice public class SomethingControllerAdvice{ @ExceptionHandler(value = SomethingWentWrongCustomException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public void someName(){ } }
It seems to be quite elegant solution, but the code is quite.. wordy, isnt it? On the other hand, If I adopt this for whole application and create @ControllerAdvice classes, then It could have sense What do you think about it? Is there any other, maybe better approach?
I hope it is not opinion based question and I dont want it to be. I just dont want to use anti-patterns and have good practices from begginings :)