title: Spring MVC Rest Service Controller with Error Handling done right?
body: <p>I was wondering how to correctly implement a Spring Controller which is supposed to serve as a REST Service. Especially I want to try and make the interface as RESTful as possible. Also i'd like to make use of HTTP Error codes so my Clients can act accordingly.</p>
  
  <p>I was wondering how to implement my Methods, so they return JSON if everything works fine(in the body of the response) or toss a http error code as well as a custom reason why it didnt work(maybe errors that came from the DAO or the database). However I'm not sure which one is the right way? return a String and add the values to return to a Model, or return a HashMap and put my stuff in there? or return the objects directly? but then what if an error occures and i cannot return said Class? return null instead?
  I post 2-3 ways of doing it that i could imagine:    </p>
  
  <pre><code>@RequestMapping(value="/addUser", method= RequestMethod.POST)
  public String addUser(@RequestBody User user, HttpServletResponse response, Model model) throws Exception{
  
      try{
          userService.addUser(user);
          model.addAttribute("user", userService.getUser(user.getUsername(), user.getPassword()));
          return "user";
      }catch(Exception e){
          model.addAttribute("error", e.toString());
          response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
          return "error";
      }
  }
  </code></pre>
  
  <p>Or rather this way:</p>
  
  <pre><code>@RequestMapping(value="/addUser", method= RequestMethod.POST)
  public @ResponseBody Map addUser(@RequestBody User user, HttpServletResponse response){
      Map map = new HashMap();
      try{
          userService.addUser(user);
          map.put("success", true);
          map.put("username", user.getUsername());
      }catch (KeyAlreadyExistsException e){
          map.put("success", false);
          map.put("Error", e.toString());
          response.sendError(HttpServletResponse.SC_FORBIDDEN, e.toString());
      }catch(Exception e){
          map.put("success", false);
          map.put("Error", e.toString());
          response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
      }
      finally {
          return map;
      }
  }
  </code></pre>
  
  <p>I realize code is not "just right" but i cannot figure out how to make it the way it needs to be. Maybe some experiences responses would help? Thx for the support already</p>