Laravel 5 override exception handler

跟風遠走 提交于 2019-12-05 18:55:18

As mentioned before by Digitlimit here Laravel ships with default ExceptionHandler which can be overwritten. There's two ways you can do so:

Adjusting the implemented ExceptionHandler

Laravel 5.8 ships with a default ExceptionHandler implemented in app/Exceptions/Handler.php. This class extends from Illuminate\Foundation\Exceptions\Handler which is the actual Laravel implementation of the Illuminate\Contracts\Debug\ExceptionHandler interface. By removing the parent class and implementing the interface yourself you could do all the custom exception handling you'd like. I've included a small example implementation of the Handler class at the end of my answer.

Registering a new ExceptionHandler

Another way of implementing a custom ExceptionHandler is to overwrite the default configuration which can be found in bootstrap/app.php. In order to overwrite the handler specified by Larvel simply register a singleton for the Illuminate\Contracts\Debug\ExceptionHandler::class abstraction after the default one like so.

# Laravel default
$app->singleton(
    Illuminate\Contracts\Debug\ExceptionHandler::class,
    App\Exceptions\Handler::class
);

# My custom handler
$app->singleton(
    Illuminate\Contracts\Debug\ExceptionHandler::class,
    App\Exceptions\MyHandler::class
);

The result of this is that App\Exceptions\MyHandler is called in case an exception is thrown and App\Exceptions\Handler is skipped altogether.

Example ExceptionHandler

It case it's useful I've included a small example of a custom ExceptionHandler to give a global idea of it's possibilities.

namespace App\Exceptions;

use Exception;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Support\Facades\Log;
use Symfony\Component\Console\Application;

class Handler implements ExceptionHandler
{
    public function report(Exception $e)
    {
        Log::debug($e->getMessage());
    }

    public function shouldReport(Exception $e)
    {
        return true;
    }

    public function render($request, Exception $e)
    {
        return view('error.page');
    }

    public function renderForConsole($output, Exception $e)
    {
        (new Application)->renderException($e, $output);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!