Different ways to handle errors when building an API

I found that developers have two main ways when creating an API do deal with errors and status code

dev

Last updated on 6 May 2021. Created on 2 April 2021.

You might have a large experience consuming various APIs. Or you were part of one or more teams in charge of building an API to the public. By now, you probably noticed different ways of how they are constructed.

Today, my focus goes to handling errors and outputting status code.

I noticed two main ways:

  1. Each error thrown is accompanied by a specific HTTP status code.
  2. All errors return 200, followed by an error message.

Is one better than the other? I think it is a matter of preference. However, no matter which route you take, I strongly advise to always return a JSON object which contains useful info.

Quick example

{
    status: 'error',
    error: 'This went wrong'
}

If you enjoyed this article and think others should read it, please share it on Bluesky or share on LinkedIn.