I am using Laravel 11 and I want to error handling. I was did in Laravel 10 in app/Exceptions/Handler.php
. However there is no handler.php
in Laravel 11. How can I create separate custom error pages. For example admin panel have different 404 page from customer 404 page.
I was did in Laravel 10 in this style:
if ($exception instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) {
if ($request->is(['admin', 'admin/*'])) {
if ($exception->getStatusCode() == 400) {
return response()->view("admin.errors.400", [], 400);
}
if ($exception->getStatusCode() == 403) {
return response()->view("admin.errors.403", [], 403);
}
if ($exception->getStatusCode() == 404) {
return response()->view("admin.errors.404", [], 404);
}
if ($exception->getStatusCode() == 500) {
return response()->view("admin.errors.500", [], 500);
}
if ($exception->getStatusCode() == 503) {
return response()->view("admin.errors.503", [], 503);
}
}
if ($exception->getStatusCode() == 404) {
return response()->view("customer.errors.404", [], 404);
}
}
Laravel 11 'slimmed' down the application and moved a lot of the boilerplate to the framework code. Due to this, a lot of the files were removed, one of which is the ExceptionHandler
class.
But it's still fully possible to customize how expections are rendered by modifying the bootstrap/app.php
file.
Full documentation: https://laravel.com/docs/11.x/errors#rendering-exceptions
If you check the bootstrap/app.php
file, you will notice
->withExceptions(function (Exceptions $exceptions) {
//
})
This is where your expection handling code will go.
To handle the NotFoundException
, you would do
use \Symfony\Component\HttpKernel\Exception\HttpException;
// rest of the code
->withExceptions(function (Exceptions $exceptions) {
$exceptions->render(function (HttpException $exception, Request $request) {
if ($request->is(['admin', 'admin/*'])) {
if ($exception->getStatusCode() == 400) {
return response()->view("admin.errors.400", [], 400);
}
if ($exception->getStatusCode() == 403) {
return response()->view("admin.errors.403", [], 403);
}
if ($exception->getStatusCode() == 404) {
return response()->view("admin.errors.404", [], 404);
}
if ($exception->getStatusCode() == 500) {
return response()->view("admin.errors.500", [], 500);
}
if ($exception->getStatusCode() == 503) {
return response()->view("admin.errors.503", [], 503);
}
}
if ($exception->getStatusCode() == 404) {
return response()->view("customer.errors.404", [], 404);
}
});
})