Creating custom error page in Lumen

2019-03-16 03:40发布

问题:

How do I create custom view for errors on Lumen? I tried to create resources/views/errors/404.blade.php, like what we can do in Laravel 5, but it doesn't work.

回答1:

Errors are handled within App\Exceptions\Handler. To display 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 in the top of the Handler.php file:

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

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



回答2:

The answer by lukasgeiter is almost correct, but the response made with the view function will always carry the 200 HTTP status code, which is problematic for crawlers or any user agent that relies on it.

The Lumen documentation tries to address this, but the code given does not work because it is copied from Laravel's, and Lumen's stripped down version of the ResponseFactory class is missing the view method.

This is the code which I'm currently using.

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 you have your errors stored in the errors directory under your views.



回答3:

It didn't work for me, but I got it working with:

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

You might also want to add

http_response_code(404) 

to tell the search engines about the status of the page.