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.
- 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.
You can drastically improve the error responses of your API by doing both of the following;
- Sticking to HTTP Status Code rules
- 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.
try/catch block at the last layer of the API then subsequently catches any raised