Creating A Custom Exception Class And Custom Handler Class In Laravel 5.3
Answer :
Laravel calls the render
function of App\Exceptions\Handler
class. So overriding it will not work.
You have to add it in App\Exceptions\Handler
class only.
For example:
<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Auth\AuthenticationException;
use App\Project\Frontend\Repo\Vehicle\EloquentVehicle;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
\Illuminate\Auth\AuthenticationException::class,
\Illuminate\Auth\Access\AuthorizationException::class,
\Symfony\Component\HttpKernel\Exception\HttpException::class,
\Illuminate\Database\Eloquent\ModelNotFoundException::class,
\Illuminate\Session\TokenMismatchException::class,
\Illuminate\Validation\ValidationException::class,
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $exception
* @return void
*/
public function report(Exception $exception)
{
parent::report($exception);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $exception
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $exception)
{
if($exception instanceof CustomException) {
return $this->showCustomErrorPage();
}
return parent::render($request, $exception);
}
protected function showCustomErrorPage()
{
$recentlyAdded = app(EloquentVehicle::class)->fetchLatestVehicles(0, 12);
return view()->make('errors.404Custom')->with('recentlyAdded', $recentlyAdded);
}
}
In new versions of Laravel, you can create a custom handler using this command:
php artisan make:exception CustomException
Then you should call these methods "report(), render()" inside your custom handler and they will override the existing ones in the App\Exceptions\Handler
.
report() used if you want to log the errors.
render() used if you want to redirect back with error or return HTTP response (like your own Blade file) or if you're building an API.
For more information, you can check Laravel documentation.
Comments
Post a Comment