Errors are a fact of life. Users will enter nonsense into your system, not because they are idiots (although it does often look that way), but because their expectations and understanding is different to 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.
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 segfault!). If your system does return HTML messages when things go wrong, that is a bug and needs fixing. If we send an unexpected format, the client may not be unable to understand the response and any error information contained in it.
In order to be able to handle this requirement, we can follow some established patterns when designing our API that may help. Many modern applications have some kind of “front controller” pattern, where 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 ...