Quick Improve: Better Error Responses

Quick Improve is a daily series of quick-to-implement, easy-to-expand improvements you can make right now to at least one code base you are working on.

The Situation

  • You have an API. This API throws errors.
  • You want to provide contextual error responses that not only follow HTTP best practises, but also let the user know some more specifics around the error itself.
  • Currently, you’re just throwing an Internal Server 500.

The Solution

You can drastically improve the error responses of your API by doing both of the following;

  1. Sticking to HTTP Status Code rules
  2. Creating an error code enum — whether its a native implementation of the concept in your language of choice (C#) or simply a static dictionary (python).

The first part, more often than not, requires the second part to be implemented properly. The second point can seem like a daunting task — especially if your API call touches a number of files all which could raise an exception that breaks the request — but it’s actually much easier then you would think.

The solution is to create a custom exception along the lines of CapturedError and inside of that exception class, store the error code enum. Whenever there’s a piece of validation or an operation that could cause an error, simply do a try/catch block, and using your error code enum and perhaps a string, you can store that contextual information for the end user.

Finally, a try/catch block at the last layer of the API then subsequently catches any raised CapturedError ‘s.