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

标签 php mysql

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

我现在将 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 block 。

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.*/
}

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

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

关于php - 处理数据库错误的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29005255/

相关文章:

php - symfony 3 - 生成具有不同语言环境的当前 url

php - 如何从另一个 Controller 操作中访问 Controller 操作?

php - 以正确的顺序从 mySQL 数据库中排序条目 - 变音符在字符 "Z"之后

mysql - 基于连接添加列

mysql - 连接表的平均值

php - mysql - 查询显示刚刚添加的记录

php - 如何从 ISBN 号中获取书名?

php - 在 PHP 中动态转义

php - DQL 的嵌套条件

mysql 将不存在的记录显示为 0