laravel / ideas

Issues board used for Laravel internals discussions.
938 stars 28 forks source link

[Proposal] Error handler middleware #853

Open ojhaujjwal opened 7 years ago

ojhaujjwal commented 7 years ago

I have had cases when a single global error handler is not enough. A lot of cases error handler for specific routes seem really handy.

For example, ApiErrorHandler for /api based routes.

This can also be handy for modules having their own error handler which can be registered in a chain of error handling middlewares.

For example: https://zendframework.github.io/zend-stratigility/error-handlers/

deleugpn commented 7 years ago

Seems like what you want might be After Middleware?

brayniverse commented 7 years ago

If I understand what you mean. You can implement this in your own application. All you need to do is create a middleware that wraps $next($request) in a try / catch block.

public function handle($request, Closure $next)
{
    try {
        return $next($request);
    } catch (ApiException $e) {
        // handle API error
    }
}

Then just add this middleware to any routes you want to be handled by this middleware.

ojhaujjwal commented 7 years ago

@deleugpn can you be a little bit more specific?

ojhaujjwal commented 7 years ago

@brayniverse I have tried that. In fact, I have used that. It used to work in Laravel 5.1. It stopped working after upgrading the application to Laravel 5.3. It went unnoticed until we got error logs in production.

Now, instead of catching exception, exception instance can be obtained after next call with:

$response = $next($request);
$exception = $reponse->exception;

But, in the second line, the response is the one prepared by the exception handler instance which is not what I am looking for here. I am looking for an error middleware mechanism to handle to handle errors on route basis.

You can check out the error handler for zend-stratigility