[英]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.