laravel 5渲染AccessDeniedHttpException

时间:2018-01-26 13:55:40

标签: laravel exception exception-handling

为什么不以给定方式呈现?除AccessDeniedHttpException

外,其他类型的异常都运行良好

应用/异常/ 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做原始渲染。

任何解决方案?

2 个答案:

答案 0 :(得分:4)

尝试将其添加到您的App\Exceptions\Handler.php中。确保在use Illuminate\Auth\Access\AuthorizationException;的顶部添加Hander.php

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);
}

答案 1 :(得分:0)

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.
    }