为什么laravel中ExceptionHandler中的render函数不执行?

问题描述 投票:0回答:4

我想显示页面

500 internal server error
页面,但不是显示报告或渲染,而是显示典型的 Laravel 异常视图和错误消息。

public function report(Exception $exception)
{
    parent::report($exception);
}

/**
 * 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)
{

  //  $exception = FlattenException::create($exception);
    $statusCode = $exception->getStatusCode($exception);
    dd($statusCode);

    if ($statusCode === 404 or $statusCode === 500) {
        return response()->view('errors.' . $statusCode, [], $statusCode);
    }
    return parent::render($request, $exception);
}
php laravel exception exceptionhandler
4个回答
1
投票

如果您看到有关 500 错误的 woops 消息,而不是 500 错误页面,这是因为应用程序处于调试模式。

在您的

.env
文件中编辑以下行

APP_DEBUG=true

成为

APP_DEBUG=false

1
投票

由于这个问题相对较新,我认为您正在起诉 Laravel 版本 7 或 8。 这是因为你的渲染函数:

function render($request, Exception $exception) 

在您的 Handler 类扩展的原始 ExceptionHandler 类中,渲染函数如下所示:

public function render($request, Throwable $e);

父类需要第二个参数是Throwable类型,但是你在子类中使用了Exception类型。


0
投票

您能否检查您的

bootstrap/app.php
文件以查看异常处理程序是否正确绑定?默认配置是like this

不久前我写了一篇关于在 Larvel 中实现自定义异常处理程序的文章,它可能包含一些对您的问题有用的信息。


0
投票

以下是如何修改 render() 方法以显示 500 个错误的自定义错误页面,并让 Laravel 处理其余部分

use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

public function render($request, Exception $exception)
{
    if ($exception instanceof ModelNotFoundException) {
        return response()->view('errors.404', [], 404);
    } elseif ($exception instanceof NotFoundHttpException) {
        return response()->view('errors.404', [], 404);
    } elseif ($exception instanceof HttpException && $exception->getStatusCode() == 500) {
        return response()->view('errors.500', [], 500);
    }

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

确保在 resources/views/errors 目录中为 error.404 和 error.500 创建了错误视图文件。

© www.soinside.com 2019 - 2024. All rights reserved.