我使用spatie权限模块来控制我网站中的角色和权限。我在Authenticate中间件中添加了一些内容。我的句柄现在看起来像这样:
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->guest())
{
if ($request->ajax() || $request->wantsJson())
return response('Unauthorized.', 401);
return redirect()->guest('login');
}
if ( ! Auth::user()->can('access acp') )
{
if ($request->ajax() || $request->wantsJson())
return response('Unauthorised.', 403);
abort(403, "You do not have permission to access the Admin Control Panel. If you believe this is an error please contact the admin who set your account up for you.");
}
return $next($request);
}
因此,如果用户未登录,我们会将其发送到登录页面,否则我们会检查是否有权访问acp,如果没有显示403错误。我已将403.blade.php添加到views / errors文件夹中。但是,当我运行该代码时,我得到一个哎呀!并且开发人员工具显示正在返回500 ISE。我不明白为什么我没有看到自定义错误页面。
到目前为止,我已尝试将环境切换到生产状态并关闭调试模式,但这并未显示该页面。我也试过抛出授权例外,但这并没有做任何不同的事情。我也尝试过使用App::abort()
,但我仍然有500 ISE。
我已经尝试了Google搜索问题,但我无法找到其他人遇到此问题。我真的很感激能帮到你的工作。
哎呀回归
如果我这样修改代码
try
{
abort(403, "You do not have permission to access the Admin Control Panel. If you believe this is an error please contact the admin who set your account up for you.");
} catch ( HttpException $e )
{
dd($e);
}
然后我得到了HttpException
的实例,其中包含我的错误代码和消息,那么为什么不显示自定义错误页面呢?
答案 0 :(得分:5)
我已经设法通过下面的代码解决了这个问题(注意它是一个流明的应用程序,但它应该与Laravel一起工作)
routes.php文件
$app->get('/test', function () use ($app) {
abort(403, 'some string from abort');
});
资源/视图/错误/ 403.blade.php
<html>
<body>
{{$msg}}
<br>
{{$code}}
</body>
</html>
app / Exceptions / Handler.php,修改render()函数如下
public function render($request, Exception $e)
{
if ($e instanceof HttpException) {
$statusCode = $e->getStatusCode();
if (view()->exists('errors.'.$statusCode)) {
return response(view('errors.'.$statusCode, [
'msg' => $e->getMessage(),
'code' => $statusCode
]), $statusCode);
}
}
return parent::render($request, $e);
}
根据文档
执行Laravel应该做的事情