Best Practices for API Error Handling
There's no right or wrong number of status codes to incorporate in your API; just stick to REST error handling practices and give the client sufficient detail.
Join the DZone community and get the full member experience.Join For Free
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 Help
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
You 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.
Published at DZone with permission of Vineet Joshi, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.