laravel 如何从laravel5中的中间件抛出禁止的异常?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28805680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:03:03  来源:igfitidea点击:

How throw forbidden exception from middleware in laravel5?

phpexceptionlaravelmiddlewarelaravel-5

提问by gsk

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:

我正在 Laravel 5 中编写一个中间件。我想从中间件中抛出一个代码为 403 的禁止异常。我的中间件功能如下:

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?

我正在从控制器调用我的中间件,但收到代码为 500 但不是 403 的错误消息。我该如何解决这个问题?

回答by lukasgeiter

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

您可以简单地使用abort()帮助程序。(或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\Handlerby overriding render()For example:

您可以App\Exceptions\Handler通过覆盖render()在内部处理这些异常,例如:

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