title: Error Code or Exception: How to communicate errors from model to controller in my case?
body: <p>In my service layer I have a method to login a user into the system. This method receives 3 arguments: <code>String username</code>, <code>String password</code>, <code>int roleId</code>. </p>
  
  <p>I need to perform couples of check in my service layer: <br></p>
  
  <ul>
  <li>A <em>User</em> exist in the system with the <code>username</code> parameter. </li>
  <li>The Password of the <em>User</em> matches with the <code>password</code> parameter. </li>
  <li>A <em>Role</em> exist in the system with the <code>roleId</code> parameter. </li>
  <li>The <em>User</em> has access to the <em>Role</em> with the <code>roleId</code> parameter. </li>
  <li>The <em>User</em> is not locked.
  ...</li>
  </ul>
  
  <p>If any of these checks fail then the service layer should tell the controller that the login has failed and why it has failed. <br>
  If all of these checks pass then the service layer should tell the controller that the login has passed. </p>
  
  <p>My concern is in case of a check fail, how can I communicate it from the service layer to the controller. Should I throw an exception? Or should I send an error code? </p>
  
  <p>I think I have these options:</p>
  
  <h2>OPTION 1:</h2>
  
  <p>Throw an exception whenever a check fail. So my service method could be:</p>
  
  <pre><code>public void login(String username, String password, int roleId) throws UserServiceException;
  </code></pre>
  
  <p>And this could be the logic:</p>
  
  <pre><code>boolean check1Flag = isUserExist(username);
  if (!check1Flag) {
     throw new UserServiceException("No user exist with username '" + username + "'");
  }
  ...
  </code></pre>
  
  <h2>OPTION 2:</h2>
  
  <p>Send an error code whenever a check fail. If all of these checks pass then send 0 as code. So my service method could be:</p>
  
  <pre><code>public int login(String username, String password, int roleId) throws UserServiceException;
  </code></pre>
  
  <p>And this could be the logic:</p>
  
  <pre><code>boolean check1Flag = isUserExist(username);
  if (!check1Flag) {
     return -1; // -1 means No user exist with username paramter
  }
  ...
  </code></pre>
  
  <h2>OPTION 3:</h2>
  
  <p>Send <code>false</code> whenever a check fail. If all of these checks pass then send <code>true</code>. So my service method could be:</p>
  
  <pre><code>public boolean login(String username, String password, int roleId) throws UserServiceException;
  </code></pre>
  
  <p>And this could be the logic:</p>
  
  <pre><code>boolean check1Flag = isUserExist(username);
  if (!check1Flag) {
     return false; 
  }
  ...
  </code></pre>
  
  <p>Option 3 looks clean but I dont know how to inform controller which error occurred in this case.</p>
  
  <p>Are there any other options? Are there any generally accepted design guidelines for this scenario? </p>
  
  <p>Thanks</p>