title: Better approach to return HttpStatus code Spring REST
body: <p>I develope rest service using spring for a long time, and till now my approach to return http status code was like this:</p>
  
  <pre><code>    @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
          }
      }
  </code></pre>
  
  <p>But I am sure there is a better way to do this. I know that we have <strong>@ResponseStatus</strong> annotation, but it is.. static, I mean it returns always <strong>the same code</strong> - but what if something would have gone wrong? Then I dont want for example, to have 200 OK as response code.</p>
  
  <p>I found the solution like this: add <strong>@ResponseStatus</strong> as static response code, but when something goes wrong in the controller, then <strong>throw some custom exception</strong> and catch it in new <strong>@ControllerAdvice class</strong>, and there also add @ResponseStatus annotation and return proper code.</p>
  
  <pre><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..");
          }
      }
  </code></pre>
  
  <p>And then catch it in the class like:</p>
  
  <pre><code>@ControllerAdvice
  public class SomethingControllerAdvice{
      @ExceptionHandler(value = SomethingWentWrongCustomException.class)
      @ResponseStatus(HttpStatus.BAD_REQUEST)
      public void someName(){
      }
  }
  </code></pre>
  
  <p>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?</p>
  
  <p>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 :)</p>