Laravel 5渲染AccessDeniedHttpException

3
为什么它没有按照给定的方式呈现?AccessDeniedHttpException 以外的其他类型异常都正常工作。
App/Exceptions/Handler.php
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException as AccessDeniedHttpException;
... 

/**
 * Render an exception into an HTTP response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Exception  $exception
 * @return \Illuminate\Http\Response
 */
public function render($request, Exception $exception)
...
            // 403 Forbidden
            if ($exception instanceof AccessDeniedHttpException)
            {
                return response()->json([
                    'code' => 403,
                    'message' => 'This action is unauthorized1.',
                ],403);
            }
            // 401 Unauthorized
            if ($exception instanceof AuthenticationException)
            {
                return response()->json([
                    'code' => 401,
                    'message' => 'Unauthenticated error.',
                ],  401);
            }

401 工作得很好,但 403 做原始渲染。
有什么解决方案吗?

你能粘贴完整的Handle.php文件吗?以及403是在哪里抛出的? - aimme
由于文件过长,此处提供链接:https://gitlab.com/praad/blogapi/blob/master/app/Exceptions/Handler.php - Prancz Ádám
如果我尝试更新未授权用户的数据(使用Postman请求进行测试),框架生成错误,但我不会将其抛出。 - Prancz Ádám
因此,请处理 Illuminate\Auth\Access\AuthorizationException; - aimme
3个回答

14

尝试将以下代码添加至您的 App\Exceptions\Handler.php 文件中。确保在 Handler.php 文件的顶部添加 use Illuminate\Auth\Access\AuthorizationException;

protected $dontReport = [
    \Illuminate\Auth\Access\AuthorizationException::class,
];

显然,AccessDeniedHttpExceptionAuthorizationException的一个实例。

public function render($request, Exception $exception)
{
    //Useful since some methods cannot be accessed in certain URL extensions
    if ($exception instanceof AuthorizationException) {
        return response()->view('errors.404', [], 404);
    }

    return parent::render($request, $exception);
}

2
class CouponStoreRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;//please change the authorize return to true in request file.
    }

1
虽然这段代码可以解决问题,但包括解释它如何以及为什么能够解决问题将有助于提高您帖子的质量,可能会得到更多的赞。请记住,您正在回答未来读者的问题,而不仅仅是现在提问的人。请[编辑]您的回答,添加解释并指出适用的限制和假设。 - Suraj Rao

0

仅对@Josh D.所说的进行详细说明:

这段代码在API上对我有效:

 public function render($request, Throwable $exception)
{
    if ($exception instanceof AuthorizationException) {
        return response()->json([
            'message' => 'You don\'t have access to this resource!'
        ],401);
    }

    return parent::render($request, $exception);
}

对我来说,我无法渲染Exception,所以我不得不使用Throwable


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接