title: Controlling exception flow in controller spring MVC
body: <p>What is the good practice in controllin exception flow in spring MVC?</p>
  
  <p>Lets say i have DAO class that saves object into database but throws exception if some rule is violated, e.g name is too long, age is too low, </p>
  
  <pre><code>@Entity
  class A{
    @Id
    @GeneratedValue
    private long id;
  
    @Column(nullable=false,length=10)
    private String name;
  }
  
  class A_DAO{
    public void save(A a) throws ConstraintViolationException{ persistance.save(a)}
  }
  </code></pre>
  
  <p>Now if i want to save A that has longer name than 10 it should throw exception.</p>
  
  <p>Howver having a dataManipulator object</p>
  
  <pre><code>class A_DataManipulator{
    public Something save(A a ){
      try{
         a_dao.save(a);
      }
      catch(ConstraintViolationException e){
         return new ObjectThatHasExceptionDescription();
      }
      return new SomethingThatSaysItsok()
    }
  
  }
  </code></pre>
  
  <p>and controller</p>
  
  <pre><code>@RequestMapping(value = "/addA", method = RequestMethod.POST)
  @ResponseBody
  public Something addA(@RequestBody A a){
     return a_data_manipulator.save(a)
  }
  </code></pre>
  
  <p>I would like to keep controller without throwing exceptions ( as i heard was good practice).</p>
  
  <p>But my question is, in this case, how would <code>A_Data_Manipulator</code> look like?
  In case of exception, i would like to return some status(404/500 etc) and some custom message. In case of success i would like to just return 200.</p>
  
  <p>I suppose i could create something like this:</p>
  
  <pre><code>class Message{
   public String msg;
   Message(String s) { this.msg = s}
  }
  
    class A_Data_Manipulator{
                public Message save(A a ){
                try{
                   a_dao.save(a);
                }catch(ConstraintViolationException e){
                 return new Message("some violation");
                }
               return null; 
            }
          }
  
  // controller annotations
  public ResponseEntity add(A a){
    Msg m = a_data_manipulator.save(a);
    if( m == null )
      return new ResponseEntity(HttpStatus.OK);
    return new ResponseEntity(HttpStatus.BAD_GATE,msg);
  
  }
  </code></pre>
  
  <p>This in my opinion is too "forced", is there any way how to create such behavior?</p>
  
  <p>Thanks for help!</p>