41

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?

hatef
  • 5,491
  • 30
  • 43
  • 46
gsk
  • 2,329
  • 8
  • 32
  • 56

1 Answers1

56

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);
}
lukasgeiter
  • 147,337
  • 26
  • 332
  • 270
  • thank you.. I am developing REST APIs,so I want to generate json response.How it is possible? – gsk Mar 02 '15 at 09:53
  • I want to catch all these from exception handler as like `if ($e instanceof ModelNotFoundException || $e instanceof NotFoundHttpException || $e instanceof MethodNotAllowedHttpException) { return new JsonResponse($error_response, 404); }` – gsk Mar 02 '15 at 10:00
  • It is not working,but I have written some my own exception classes and now I am using the same. – gsk Mar 02 '15 at 10:39
  • Did you `use` the `Symfony\Component\HttpKernel\Exception\HttpException`? Because that's what `abort()` throws. – lukasgeiter Mar 02 '15 at 10:46