Slim: Extract error handling to middleware

Created on 19 Nov 2016  路  4Comments  路  Source: slimphp/Slim

Slim 4

Most helpful comment

I'd like to apply middleware after error handler is triggered.

My use case is adding CORS headers in REST API.
At this moment I can easily add middleware to group routes, but when returing response Not Found, I have to add CORS headers within error handler.

I'm mentioning it here is because I believe that wrapping middleware around error handlers makes more sense to me than wrapping error handlers around middleware.

All 4 comments

I assume the idea here is to delegate error handling to a middleware else to PHP itself outside of the Slim app context. For the middleware, do we intend for that to be a diagnostic-type error handler that reports the stack trace? Or did we intend for that to be a production-ready middleware (e.g. "something went wrong, we're on it")? Or perhaps two separate middlewares?

/cc @akrabat @silentworks @geggleto

In my own experiences having 2 middlewares turn out to be impractical because it would mean having to build 2 different "HTTP stacks" (list of middlewares & routes) for dev or prod.

If that's of any interest here is what I did: a single error handler middleware that would ask a responder to generate a response: the responder injected in the middleware would depend on DIC configuration (https://github.com/stratifyphp/error-handler-module/tree/master/src/ErrorResponder). That implies not instantiating the middleware directly but rather relying on a DIC, else we are back to the problem I mentioned above.

Edit: that also allows users to customize the "responder" if they want to generate a different error page, after all the responder is just like a controller. It could be called controller if that's clearer too.

@mnapoli That's a good point.

I'd like to apply middleware after error handler is triggered.

My use case is adding CORS headers in REST API.
At this moment I can easily add middleware to group routes, but when returing response Not Found, I have to add CORS headers within error handler.

I'm mentioning it here is because I believe that wrapping middleware around error handlers makes more sense to me than wrapping error handlers around middleware.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Paratron picture Paratron  路  24Comments

grikdotnet picture grikdotnet  路  54Comments

zyx-rd picture zyx-rd  路  19Comments

akrabat picture akrabat  路  43Comments

l0gicgate picture l0gicgate  路  31Comments