Detailed explanation of the method of abnormal pages such as laravel framework configuration 404 (code example)

01-28-2024

What this article brings to you is a detailed explanation (code example) of the method of configuring 404 and other abnormal pages in laravel framework, which has certain reference value. Friends who need it can refer to it and hope to help you. All exceptions in Laravel are handled by the Handler class, which contains two methods: report and render, in which the render method renders the exceptions to the http response. Laravel's Handler class file location: app/Exceptions/Handler. Because the render method is rendered to the http response abnormally in time, we only need to modify the render method. Many methods on the Internet are to modify the render method to:

public function render($request, Exception $exception) { if ($exception) { return response()->view('error.'.$exception->getStatusCode(),

This is because if you visit the page that must be logged in, you will enter the render method of app/Exceptions/Handler.php, and at this time $exception->getStatusCode () does not exist, and an error will be reported at this time, so how to solve it?

At this time, we found the method of parent::render:

At this time, we found that the original laravel framework has included our situation, so we can change the above method to:

public function render($request, Exception $exception) { if (! ($exception instanceof AuthenticationException)) { return response()->view('error.'.$exception->getStatusCode(), [],$exception->getStatusCode()); } return parent::render($request, $exception); }

At this time, this problem is solved perfectly, and then a new error page is created under resources/view/error/. The name of the error page is: {errorcode} ... balde.php, where the errorcode is an error code, such as 404 ... balde.php.

When you visit a nonexistent route after configuration, you can jump to the 404 page you configured.

Copyright Description:No reproduction without permission。

Knowledge sharing community for developers。

Let more developers benefit from it。

Help developers share knowledge through the Internet。

Follow us