繁体   English   中英

Laravel 9 如果数据库连接失败则抛出自定义错误视图?

[英]Laravel 9 throw custom error view if DB connection fails?

我想做的是,如果与数据库的连接失败,而不是No connection could be made because the target machine actively refused it ,我想抛出一个自定义视图,显示一个简单的 h1,其中包含连接失败的文本. 我怎样才能做到这一点?

您可以通过修改您的app/Exceptions/Handler.php来捕获该特定错误来执行此操作:

public function render($request, Throwable $exception) {
    if ($exception instanceof QueryException) {
        return response()->view('errorpage');
    }

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

当然,您可以将QueryException更改为您想要处理的任何异常,例如: Illuminate\Database\Eloquent\ModelNotFoundException或任何其他异常。

app/Exceptions/Handler.php

use PDOException;
use App\Exceptions\Handler;

class ExceptionHandler extends Handler
{
    public function render($request, Exception $exception)
    {
        if ($exception instanceof PDOException) {
            return response()->view('errors.database', [], 500);
        }

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

resources/views/errors , errors.database中,您可以创建自定义样式

答案在顶部给出,但我对其进行了一些修改。

use Throwable;
use PDOException;

public function render($request, Throwable $exception)
{
    if ($exception instanceof PDOException) {
        return response()->view('errors.database', [], 500);
    }

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM