[英]Laravel 9 throw custom error view if DB connection fails?
what i am trying to do is if the connection to the database fails, instead of getting No connection could be made because the target machine actively refused it
, i want to throw a custom view that displays a simple h1 with the text that the connection fails.我想做的是,如果与数据库的连接失败,而不是
No connection could be made because the target machine actively refused it
,我想抛出一个自定义视图,显示一个简单的 h1,其中包含连接失败的文本. How can i do that?我怎样才能做到这一点?
You can do this by modifying your app/Exceptions/Handler.php
to catch that specific error:您可以通过修改您的
app/Exceptions/Handler.php
来捕获该特定错误来执行此操作:
public function render($request, Throwable $exception) {
if ($exception instanceof QueryException) {
return response()->view('errorpage');
}
return parent::render($request, $exception);
}
Of course you can change the QueryException
to any exception that you want to handle, such as: Illuminate\Database\Eloquent\ModelNotFoundException
or any other.当然,您可以将
QueryException
更改为您想要处理的任何异常,例如: Illuminate\Database\Eloquent\ModelNotFoundException
或任何其他异常。
In app/Exceptions/Handler.php
在
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);
}
}
In resources/views/errors
, errors.database
, you can create custom style在
resources/views/errors
, errors.database
中,您可以创建自定义样式
The answer was given at the top, but i made it work with some modifications.答案在顶部给出,但我对其进行了一些修改。
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.