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);
}
}