Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How throw forbidden exception from middleware in laravel5?

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?

like image 918
gsk Avatar asked Mar 02 '15 08:03

gsk


1 Answers

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);
}
like image 104
lukasgeiter Avatar answered Oct 05 '22 02:10

lukasgeiter