Chapter 12. Error Handling in APIs

Errors are a fact of life. Users will enter nonsense into your system, not because they are simpletons (although it does often look that way), but because their expectations and understanding are different from yours. The Internet is a very loosely-coupled affair and all kinds of things can and will go wrong at a technical level, once in a while. How your API handles these inevitable situations is a measure of the quality and design of your API, so this chapter gives some pointers on what to look out for and how to do it well.

Output Format

This is the golden rule: always respond in the format that the client was expecting. This means that it is never acceptable to return an HTML error message when the client expected JSON (in fact, in certain PHP versions, passing invalid JSON to json_decode() causes a segment fault!). If your system does return HTML messages when things go wrong, that is a bug and needs fixing. If an unexpected format is sent, the client will not be unable to understand the response and any error information contained in it.

In order to handle this requirement, there are some established patterns when designing our API that may help. Many modern applications have some kind of “front controller” pattern, in which all incoming requests are handled by a common entry point. This common front controller typically parses the request and figures out which part of the system it should be passed on to. We can put the same ideas into practice ...

Get PHP Web Services now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.