title: Error Handling in REST API: Best Practice
body: <p>I am trying to develop a rest api that basically return information about country. So my url will be something like </p>
  
  <p><a href="http://myrestservice/country/US" rel="nofollow noreferrer">http://myrestservice/country/US</a></p>
  
  <p>so when a request come with valid country, my rest service will prepare information for that country and prepare  object called <code>countryInfo</code> and return this as </p>
  
  <pre><code>return  ResponseEntity.status(200).body(countryInfo);
  </code></pre>
  
  <p>now say user send request as
  <a href="http://myrestservice/country/XX" rel="nofollow noreferrer">http://myrestservice/country/XX</a>. In this case since XX is not valid country i have send response. I read in different place and most of them only explain about status code. My question is what is the best way to return error.</p>
  
  <ol>
  <li><code>return  ResponseEntity.status(404).body("Invalid Country");</code></li>
  <li><p><code>return  ResponseEntity.status(404).body(myobject);</code> //here myObject will be <code>null</code>.</p></li>
  <li><p>Prepare a Class say <code>MyResponse.java</code> as below.</p>
  
  <pre><code>public class MyResponse {
  
    private String errorCode;
    private String errorDescription;
    private CountryInfo countryInfo 
  
  }
  </code></pre></li>
  </ol>
  
  <p>And return this object no matter if there are  error or not. If there is error set <code>errorCode</code> and <code>errorDescription</code> field with proper value  and set <code>countryInfo</code> to null and for no error set <code>errorCode</code> and <code>errorDescription</code> as empty and <code>countryInfo</code> with data.</p>
  
  <p>Which of the above option is considered standard way to handle error.</p>