【问题标题】:Laravel returning HttpException object instead of showing custom error pagesLaravel 返回 HttpException 对象而不是显示自定义错误页面
【发布时间】:2016-10-23 02:30:54
【问题描述】:

我正在使用 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 错误。我在views/errors 文件夹中添加了一个403.blade.php。但是,当我运行该代码时,我只会得到一个哎呀!并且开发人员工具显示正在返回 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 实例,那为什么不显示自定义错误页面?

【问题讨论】:

  • 您在 500 上看到什么异常消息?
  • 它向我显示了我传递给中止的消息,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.
  • 你检查你的 PHP 错误日志了吗? 500 表示我们正在讨论更高级别的错误。
  • 虽然开发者工具说它是 500 我不确定是不是,我只是认为它返回了一个不正确的代码。没有日志文件,不知道为什么。我正在使用 PHP7 在 Xampp 上运行,但日志文件夹为空。
  • 安装 xdebug 并设置一些断点,不太可能有人远程帮助调试

标签: php error-handling laravel-5.2


【解决方案1】:

我已经通过下面的代码解决了这个问题(请注意,它是一个 Lumen 应用,但它应该可以与 Laravel 一起使用)

routes.php

$app->get('/test', function () use ($app) {
    abort(403, 'some string from abort');
});

resources/views/errors/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 根据文档应该做的事情

【讨论】:

  • 谢谢!做到了。那真是让人头疼。我猜我在输入 Whoops 时覆盖了原来的内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-21
  • 1970-01-01
  • 2020-11-16
  • 2017-08-10
  • 2018-11-22
  • 2018-07-04
  • 1970-01-01
相关资源
最近更新 更多