英文:
Laravel 9 throw custom error view if DB connection fails?
问题
我想要做的是,如果与数据库的连接失败,而不是出现“无法建立连接,因为目标机器主动拒绝了连接”的错误,我想要抛出一个自定义视图,显示一个简单的h1标签,其中包含连接失败的文本。我该如何做?
英文:
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. How can i do that?
答案1
得分: 1
你可以通过修改你的 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
或其他异常类型。
英文:
You can do this by modifying your app/Exceptions/Handler.php
to catch that specific error:
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.
答案2
得分: 1
在 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
,你可以创建自定义样式。
英文:
In 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
答案3
得分: 0
以下是翻译好的部分:
答案已经在顶部给出,但我通过一些修改使其正常工作。
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);
}
英文:
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);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论