In a post to his site Alejandro Celaya shares a method he worked up for creating a content-based error handler in Zend Expressive - a method of changing the error output based on the content it was passed and the Accept
header provided.
In one of my tests of the REST API I saw that when an error occurs (404, 405 or 500), I was getting an HTML response, which is not easy to handle when the client is expecting JSON.I started to dig on how to fix this problem and thought that using ErrorMiddleware (which is invoked in case of an error) should be the solution, but after some tests I saw that it is only invoked if a regular middleware invokes the next one by passing an error as the third argument or an uncaught exception is thrown. When a route is not matched (404) or it is matched with an incorrect HTTP method (405), the error middleware is not invoked.
After confirming (on Twitter) that this was the intended result he went about looking for another option. He looked into using "Final Handlers" that are called when nothing else matches in the middleware execution chain. They didn't provide one for JSON handling, however, so he had to create his own (code is included in the post) and explains a bit of how it's handling the data and HTTP response code. Unfortunately using this handler made the error output always return JSON so another piece was needed, the content-based detection handler that switches between types based on the Accept
header.