user6122500
user6122500

Reputation: 942

How to catch authorization errors in Laravel's Handler render

I'm trying to show a custom error page, which I'd like to appear if the error wasn't a 'page not found' or a authentication issue (e.g. trying to access a page which the user doesn't have access to). I'm using the code below in Laravel 5.3's Handler.php. While the 404 part works, the authentication part doesn't (triggering this error just returns the 500 page instead). What am I missing?

public function render($request, Exception $e)
{
    if ($e instanceof NotFoundHttpException || $e instanceof AuthorizationException || $e instanceof AuthenticationException) {
        return parent::render($request, $e);
    }
    else {
        return response()->view('errors.500', [
            'sentryID' => $this->sentryID,
        ], 500);
    }
}

Upvotes: 2

Views: 5905

Answers (1)

Sandeesh
Sandeesh

Reputation: 11906

Edit : Looks like you want to handle all the global error pages. Laravel uses symfony's exception handler to generate the error page text and style. This can be found at

vendor/symfony/debug/ExceptionHandler.php

It's used in vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php as

use Symfony\Component\Debug\ExceptionHandler as SymfonyExceptionHandler;

To handle every error and exception you can extend the method prepareResponse to app/Exceptions/Handler.php and make appropriate changes.

protected function prepareResponse($request, Exception $e)
{
    if ($this->isHttpException($e)) {
        return $this->toIlluminateResponse($this->renderHttpException($e), $e);
    } else {
        return $this->toIlluminateResponse($this->convertExceptionToResponse($e), $e);
    }
}

You can check the underlying working of this method in vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php

End edit

You don't need to mess in the render method for this. Out of the box laravel searches for error views and renders them if available based on the error code. So for 404 and 500 you could just create the following two views and customize it in there.

resources/views/errors/404.blade.php
resources/views/errors/500.blade.php

This views get the exception, status and header information for you to display if needed. They are called like so

return response()->view("errors.{$status}", ['exception' => $e], $status, $e->getHeaders());

For the authentication check. Laravel calls the unauthenticated method in app/Exceptions/Handler.php when a user is unauthenticated. This code by default redirects the users to login page or shows a json response. You can make you changes here.

protected function unauthenticated($request, AuthenticationException $exception)
{
    if ($request->expectsJson()) {
        return response()->json(['error' => 'Unauthenticated.'], 401);
    }
    return redirect()->guest('login');
}

Upvotes: 2

Related Questions