Mindful error responses

Sayeed Anjum
2 min readJun 7, 2018

Code is communication — Forget Who

Long Version

You take a coffee sip and send that POST request to the REST API you are integrating into your app. The next moment, you experience rejection.

Error: 403 Forbidden

Now what? Why would I get a 403error? This usually is an authorization issue.

Maybe I need an Authorization header. Or perhaps the authorization header format is wrong? Maybe this, maybe that.

Many hours later, there is still no progress. You get into the code to see why a 403 is being generated. Then it hits you.

Arggh! It was yet another case of mindless responses from an uncaring developer. It should have been a 422 error instead. The problem is not authorization but in the values being sent. One particular value is not allowed in the current context, and it’s failing the validation.

So why was a 403 sent? Ignorance, laziness, and mindlessness. It could even be confusion. Just because the validation method is called isPermittedStateTransition(), it doesn’t become a permission issue. It’s still a validation issue, OK?

Most developers never think of how poor communication (aka programming) can hurt productivity. This applies to all code but it’s even bigger crime in the case of REST APIs.

For validation errors use 422 instead of 400 or worse, something random.

Check out this good explainer article about 422.

Also, in this helpful article on error codes, Aniket Patel hits the nail like a pro.

Server-side error handling and communication are major, often under-appreciated components in designing a REST API. Most API developers spend their time on everything else involved in getting a REST API done right — from debating which resources need to be exposed through the API, to getting the HTTP verbage right, to using content negotiation. Unfortunately, error responses tend to be an after-thought. They’re treated as second-class citizens whose design never gets reviewed nor discussed as actively as any another component of the API. The fact is that although errors only account for a fraction of all messages sent by the API (at least typically), they are the most scrutinized messages by app developers. (Even more than success response messages!)

The article goes on to list several best practices on how to use error codes in the right way. Here is a summary from that article.

  1. Return an HTTP status code that closely matches the error condition
  2. Return human-readable error messages
  3. Return machine-readable error codes
  4. Return the Invalid parameter name
  5. Set Location
  6. Provide a Help URL

That’s all folks.

Be mindful in all that you do.

--

--