Best Practices for API Error Handling

By Vineet Joshi in Developer Posted Feb 1, 2017

What do you do when everything goes wrong with your RESTful API? You have many ways to indicate an API call failure, including the built-in status codes included in HTTP. Use these best practices to help developers with their API integration.

Good Error Codes and Messages

Nothing is more frustrating than running into an error code that doesn't tell you anything about the problem. You want readable, understandable error messages that provide developers with the necessary resources to continue forward.
 

Don't Skimp on the HelpError Handling

Do you have documentation or knowledge base articles that walk developers through the solution to an error message? Include the links for a convenient reference. If you don't have any documentation, now's a good time to go back and write all your error codes up.
 

Client Needs to Rely on Graceful Error Handling

The end user working with your API integrates it as a single piece of a much larger whole. If errors show up on their end, they need detailed error messages to promote a good user experience.
 

Tell Clients If They Can't Solve the Problem

You may have developers who assume that they caused a particular error if they don't have any other information to go off of. They try everything to fix it when it ends up being a problem on your side. Indicate whether an error is caused by something the end user controls or if they need to wait for you to address the issue.
 

How to Choose the Right Type of Error Codes

 
API Error Handling - REST APIsYou might find it handy that the HTTP protocol includes more than 70 status codes, but you need to narrow that list down to the ones you actually need. Keeping it simple is harder than it sounds.
You don't have a one-size-fits-all set of status codes that work for every RESTful API you develop. The type of data you have, the ways the client interacts with it and how your server handles the data all have an impact on your selection.
Start with the bare basics, such as:
  • 200 OK
  • 400 Bad Request
  • 500 Internal Server Error
Pay close attention to the way you interact with the API once you create this list. Every time you encounter a situation that aligns with an HTTP status code, include it with the other messages. A few common options include:
  • 401 Unauthorized
  • 403 Forbidden
There's no right or wrong number of status codes to incorporate in your API. Be prepared to work in more as the need arises. Edge cases and other unusual scenarios fall under the common sense rules. Stick to the spirit of REST error handling practices and give the client sufficient detail.
 
Read more about RESTful API design from our previous blogs:

Cloud Elements platform is built on REST APIs. Our developer portal houses all of our documentation on authetication, pagination, error handling and more.

Check Out Developer Portal