Creating a custom error page in Lumen

How to create a custom error viewer in Lumen? I tried to create resources/views/errors/404.blade.php , like what we can do in Laravel 5, but this will not work.

+6
source share
3 answers

Errors are handled within the App\Exceptions\Handler . To render a 404 page, change the render() method to this:

 public function render($request, Exception $e) { if($e instanceof NotFoundHttpException){ return response(view('errors.404'), 404); } return parent::render($request, $e); } 

And add this to the top of the Handler.php file:

 use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; 

Edit: As @YiJiang points out, the response should not only return a 404 view, but also contain the correct status code. Therefore, view() must be enclosed in a response() call passing at 404 as a status code. Like in the edited code above.

+16
source

The answer from lukasgeiter is almost correct, but the answer made using the view function will always contain an HTTP 200 status code, which is problematic for scanners or any user agent that relies on it.

The Lumen documentation is trying to solve this problem, but this code does not work, because it is copied from Laravel's and the Lumen truncated version of the ResponseFactory class ResponseFactory not have a view method.

This is the code I'm using now.

 use Symfony\Component\HttpKernel\Exception\HttpException; [...] public function render($request, Exception $e) { if ($e instanceof HttpException) { $status = $e->getStatusCode(); if (view()->exists("errors.$status")) { return response(view("errors.$status"), $status); } } if (env('APP_DEBUG')) { return parent::render($request, $e); } else { return response(view("errors.500"), 500); } } 

This assumes your errors are stored in the errors directory under your views.

+7
source

This did not work for me, but I worked with it:

 if($e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) { return view('errors.404'); } 

You can also add

 http_response_code(404) 

inform search engines about the status of the page.

0
source

Source: https://habr.com/ru/post/987188/


All Articles