php – How throw forbidden exception from middleware in laravel5?-ThrowExceptions

Exception or error:

I am writing a middleware in laravel 5. I want to throw a forbidden exception with code 403 from middleware. My middleware function is given below:

use Exception;

public function handle($request, Closure $next)
{
    if (!Auth::check()) {
        throw new Exception("Access denied", 403);
    }
    return $next($request);
}

I am calling my middleware from controller and I am getting error message with code 500 but not 403. How can I resolve this?

How to solve:

You can simply use the abort() helper. (Or App::abort())

public function handle($request, Closure $next) {
    if (!Auth::check()) {
        abort(403, 'Access denied');
    }
    return $next($request);
}

You can handle these exceptions inside App\Exceptions\Handler by overriding render() For example:

public function render($request, Exception $e)
{
    if($e instanceof HttpException && $e->getStatusCode() == 403){
        return new JsonResponse($e->getMessage(), 403);
    }    
    return parent::render($request, $e);
}

Leave a Reply

Your email address will not be published. Required fields are marked *