How to catch 404 errors in Laravel 11

Published on July 15, 2024. Last updated on January 22, 2025.
How to catch 404 errors in Laravel 11

In a recent project, we needed to catch 404 pages and log them in the database, allowing administrators to monitor and redirect these requests efficiently.

Since Laravel 11 does not include the App/Exceptions/Handler class, we needed to adopt a different approach.

 

To catch 404 exceptions, we need to edit the bootstrap/app.php file. Add the following code before the ->create() method.

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Throwable;

//...
->withExceptions(function (Exceptions $exceptions): void {
        $exceptions->respond(function (Response $response, Throwable $exception): bool {
            if ($exception instanceof NotFoundHttpException) {
                info('Catched 404');
            }

            return $response;
        });
})
->create();

You can replace the info function with your custom logic to handle the 404 error as needed.