title: returning meaningful exception to the client in RESTFul API
body: <p>I am in the process of developing some comprehensive RESTFul APIs using .net web api. </p>
  
  <p>Basically there is an existing web application running already. We are developing an mobile app for that. Since there are existing implementation, I am trying to reuse the existing business layer code as mush as possible so that it is easier to maintain in the future.</p>
  
  <p>However, I am having some issue regarding how to return the exception to the client. In the API layer, I call some business function to perform an operation. The business layer performs the operation and throw exceptions in some situation.</p>
  
  <p>e.g.</p>
  
  <pre><code>public void ResultModel Process(InputModel input) {
    if (input is not valid) {
      throw new ApplicationException("some message");
    }
    // keep on processing
  }
  </code></pre>
  
  <p>In the API layer, I am trying capture all the exceptions and then map to some pre-defined api exception </p>
  
  <p>e.g.</p>
  
  <pre><code>http response code: 404
  reason: the country information is incorrect 
  
  http response code: 404
  reason: invalid student id is provided
  </code></pre>
  
  <p>I was thinking in the API layer, i will create some error status code apart from the standard http status code.</p>
  
  <p>eg. </p>
  
  <pre><code>http response code: 404
  error code: error0001
  reason: the country code is incorrect 
  
  http response code: 404
  error code: error0002
  reason: invalid student id is provided
  </code></pre>
  
  <p>And then document meaning of the error code in the API documentation.</p>
  
  <p>However, by doing that, i need to create a mapping between the business layer exception and the api response. The business layer implementation shouldn't be aware of this kind of exception. But I might need to change all the place an exception is throw to return some exception with some exception code and the map that exception code into the api error code.</p>
  
  <p>This is what I can think of about solving the problem, but the code base that I am dealing is quite big, the effort of re factoring and implementing this solution is very big. </p>
  
  <p>I am wondering if there is any better deign and easier way of addressing the issue? Or any ideas about this will be helpful for me.</p>