Laravel package register exception handler

3.8k views Asked by At

I wonder if it's possible to register a second Exception Handler in a package in Laravel 5.

I have a package (let's call it api-serializer) that register a middleware to convert all requests to JSON (for an API) and this package register 2 helpers: success() and failure() that handle specifically the json when an error occurs (or not).

In my application exception handler I do the following:

/**
 * Render an exception into an HTTP response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Exception  $e
 * @return \Illuminate\Http\Response
 */
public function render($request, Exception $e)
{
    return failure($e->getMessage());
}

Now I have a second package (let's call it tumblr-api) that makes http calls and raise exceptions, for instance:

throw (new CustomCoolException)->setModel($model);

I would like to treat this exception differently, because the message is located in the $model, do smething like this:

if ($e instanceof CustomCoolException) {
    return failure($e->getModel()->getMessage());
}

What I don't want to do it's to add my package exception to my main exception handler, as they'll be tightly binded.

I neither want to create a dependency between my api-serializer that exposes success() and failure() to my tumblr-api package.

Is it possible, from my api-serializer to register a second ExceptionHandler or add specific switchs for it's exceptions without altering anything else ?

I would like to make my tumblr-api package as independent as possible, so the user installing it just have to register the service provider and go !

1

There are 1 answers

0
Tiago Alves On

You can override the App's Exception handler with your own package's exception handler in your package's controllers like this:

class YourPackageController extends Controller
{
    public function __construct()
    {
        \App::singleton(
            \Illuminate\Contracts\Debug\ExceptionHandler::class,
            YourExceptionHandler::class
        );
    }

Credits go to malhal at https://laracasts.com/discuss/channels/requests/custom-exception-handler-based-on-route-group