Sean Fraser
Sean Fraser

Reputation: 352

Laravel 5 controller exception handler

I have an application in which my controllers are broken up into specific groups (API, CMS and front-end), this is already set up using Router groups. My question is how would one go about creating custom error handling for each group.

For example, when an exception occurs in any API controller action I would like to send back json with an error code and message, an exception in the CMS would output a detailed error page, and an exception on the front end would send the user to a generic 404 or 500 error page (as appropriate).

I am aware of how I could do this manually in each controller action, but that might get very repetitive. Ideally, I would want to create one handler for each and automatically use it across the board.

I am also aware of the App\Exceptions\Handler class, but if any of the controller groups could return a ModelNotFoundException, for example, how do I differentiate where the exception came from?

Is there another place that this type of exception handler could be inserted?

Upvotes: 3

Views: 5500

Answers (1)

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111889

If you go to app\Exceptions\Handler.php file (which you mentioned) you can do it what you want.

You could for example define your render function this way:

public function render($request, Exception $e)
{
    $trace = $e->getTraceAsString();
    if ($e instanceof ModelNotFoundException
        && mb_strpos($trace, 'app\Http\Controllers\WelcomeController')
    ) {
        return response()->json('Exception ' . $e->getMessage());
    } elseif ($e instanceof ModelNotFoundException) {
        return "General model not found";
    }

    return parent::render($request, $e);
}

and add to imports use Illuminate\Database\Eloquent\ModelNotFoundException;

and now if you throw ModelNotFoundException in your WelcomeController or you for example run another class' method from your WelcomeController and this method will throw ModelNotFoundException you can track it and return json response. In other cases if exception will be instance of ModelNotFoundException you can render your exception in other way and in all other cases you can use standard exception method to render.

This way you don't need to define anything in your controller, you can do it just in Handler and it it's more complicated you could create separate methods or create new classes to handle specific exceptions in the way you want and run them in this handler.

Upvotes: 4

Related Questions