How throw forbidden exception from middleware in laravel5?

gsk picture gsk · Mar 2, 2015 · Viewed 20.7k times · Source

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?

Answer

lukasgeiter picture lukasgeiter · Mar 2, 2015

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);
}