Error handling middleware, plus unit tests