Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating custom error page in Lumen

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.

like image 300
Kusmayadi Avatar asked May 14 '15 08:05

Kusmayadi


2 Answers

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.

like image 83
lukasgeiter Avatar answered Oct 19 '22 20:10

lukasgeiter


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.

like image 12
Yi Jiang Avatar answered Oct 19 '22 19:10

Yi Jiang