Skip to content

Instantly share code, notes, and snippets.

@adamcrampton
Last active November 4, 2023 07:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamcrampton/c766ff9b618ce27370576988255741f6 to your computer and use it in GitHub Desktop.
Save adamcrampton/c766ff9b618ce27370576988255741f6 to your computer and use it in GitHub Desktop.
Custom error handling redirects for Laravel (App\Exceptions\Handler)
<?php
namespace App\Exceptions;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\ErrorHandler\Exception\FlattenException;
use Throwable;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that are not reported.
*
* @var array
*/
protected $dontReport = [];
/**
* A list of the inputs that are never flashed for validation exceptions.
*
* @var array
*/
protected $dontFlash = [
'password',
'password_confirmation',
];
/**
* Report or log an exception.
*
* @param \Throwable $exception
* @return void
*
* @throws \Exception
*/
public function report(Throwable $exception)
{
parent::report($exception);
}
public function render($request, Throwable $exception)
{
// Catch session expiry.
if ($exception instanceof AuthenticationException):
return redirect()->route('login')->with([
'info' => '<p>Sorry, your session has expired, please log in again.</p>'
]);
endif;
// Common errors.
$code = FlattenException::create($exception)->getStatusCode($exception);
switch ($code):
case 403:
return redirect()->route('errors.403');
break;
case 404:
return redirect()->route('errors.404');
break;
case 500:
return redirect()->route('errors.500');
break;
default:
return parent::render($request, $exception);
break;
endswitch;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment