Php 处理数据库错误的最佳方法

Php 处理数据库错误的最佳方法,php,mysql,Php,Mysql,我只是想知道捕捉数据库错误的最佳方法是什么。如果发生错误,我想向用户显示一些“对不起”的内容,并向技术支持发送电子邮件 现在,我将try-catch放在连接设置文件中,并将该文件包含在其他功能文件中。它不能正常工作 比如说,数据库连接脚本db-connect.php try { $db = new PDO('dsn', 'username', 'password'); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTI

我只是想知道捕捉数据库错误的最佳方法是什么。如果发生错误,我想向用户显示一些“对不起”的内容,并向技术支持发送电子邮件

现在,我将try-catch放在连接设置文件中,并将该文件包含在其他功能文件中。它不能正常工作

比如说,数据库连接脚本db-connect.php

try {
  $db = new PDO('dsn', 'username', 'password');
  $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch(PDOException $ex) {
echo ('An internal error happens. The technical staff has been informed to '.
      'fix this. Sorry for any inconvenience.');
errorReport(/*title=*/"Database connection failed",
            /*code=*/$ex->getCode(), /*message=*/$ex->getMessage(),
            /*trace=*/$ex->getTraceAsString(), /*file=*/$ex->getFile(),
            /*line=*/$ex->getLine());
}
然后在另一个包含db connect的文件a.php中:

require_once("db-connect.php");
$stmt = $db->prepare("SELECT * FROM user WHERE username=:username");
$stmt->excute(array(':username' => $uname));
现在我手动关闭了数据库,但用户会得到如下错误

An internal error happens. The technical staff has been informed to fix this. Sorry for any inconvenience.
Notice: Undefined variable: db in a.php on line 26
Fatal error: Call to a member function prepare() on null in a.php on line 26

我知道变量db不存在,因为它不是因为连接错误而创建的。但我该如何改进这一点呢?非常感谢您的帮助。

通常的做法是重定向到错误页面(呈现重定向或url),并向用户显示某种有用的消息。您可以重定向,以便应用程序不再能够处理潜在无效数据上的逻辑,并且仍然呈现整个页面


请看一下自定义错误处理函数,我建议您也研究一下,以避免可能不需要的输出

这取决于个人需要,以及他们希望如何显示错误。 在您的情况下,我建议您使用PHP提供的错误报告设置。对于开发服务器,您可以按如下方式使用

error_reporting(E_ALL & E_STRICT);
对于生产服务器,您可以将其用作

error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING)
因此,您的通知和警告不会显示在生产服务器上,但会显示E_错误的错误类型

现在,要处理此错误,可以使用try-catch块,正如您已经使用的那样

try {
 // Your code goes here
} catch(PDOException $ex) {
   /* Now if you have any exception in your code then you can show the 
generic message to user as 404 / not found page or woops something went wrong. Or the message you have set already as "An internal error happens. The technical staff has been informed to fix this. Sorry for any inconvenience."

With this message you can send a mail to the respective development team what exactly error comes. The email body will contain the string representation of your error message.*/
}
因此,通过这种方式,您可以向用户显示通用消息,并通过电子邮件向开发团队显示详细的错误消息。因此,无论何时发生重大异常或错误,您的团队都会收到电子邮件通知


希望这将对某人有所帮助。

您可以使用,然后在
回调中调用
die
并在
回调中显示您的消息。
好吧,您必须查看通过
errorReport
报告的错误,但出于某种原因不想向我们显示。。。