使用Laravel 5.1 Authorize方法时如何返回自定义403异常 [英] How to return custom 403 exception when using Laravel 5.1 authorize method

查看:565
本文介绍了使用Laravel 5.1 Authorize方法时如何返回自定义403异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在laravel 5.1中,如果您使用以下方法,则可以在检查能力时返回自定义响应:

In laravel 5.1 you can return a custom response when you check abilities if you use the following method:

if (Gate::denies('update', $post)) {
        return response()->view('errors.403');
}

使用authorize方法时是否有任何方法可以返回类似的自定义错误:

Is there any way to return a similar custom error when using the authorize method:

$this->authorize('update', $post);

上面的代码简单地引发了状态码为403的http异常.

The above simply throws a http exception with status code 403.

推荐答案

我可以通过以下方式实现:

I can do it in following way:

App\Http\Controllers\Controller中添加以下方法:

protected function createGateUnauthorizedException(
    $ability,
    $arguments,
    $message = 'This action is unauthorized.',
    $previousException = null
) {
    throw $previousException;
}

它将重新抛出UnauthorizedException.

现在在App\Exceptions\Handler.php中,您可以在render方法的开头添加:

Now in App\Exceptions\Handler.php you can add at the beginning of render method:

if ($e instanceof \Illuminate\Auth\Access\UnauthorizedException)  {
    return response()->view('errors.403');
}

这篇关于使用Laravel 5.1 Authorize方法时如何返回自定义403异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆