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


Best way to handle database errors

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

我现在将 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 不存在,因为它不是由于连接错误而创建的。 但是我该如何改进呢?任何帮助,不胜感激。

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

error_reporting(E_ALL & E_STRICT);

对于生产服务器,您可以将其用作

error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING)

因此,您的通知和警告将不会显示在生产服务器上,但将显示E_ERROR的错误类型。

现在要处理此错误,您可以使用 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.*/
}

因此,通过这种方式,您可以通过电子邮件向用户显示通用消息,并向开发团队显示详细的错误消息。因此,每当发生一些严重的异常或错误时,您的团队都会通过电子邮件收到通知。

希望这会帮助某人。

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

看看set_error_handler自定义错误处理函数,我建议研究输出缓存以避免可能不需要的输出。