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

时间:2015-03-12 08:47:31

标签: 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());
}

然后在另一个文件a.php中包含db-connect:

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不存在,因为它不是由于连接错误而创建的。但我怎么能改善这个呢?任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:0)

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

看看自定义错误处理函数set_error_handler,我建议调查output caching以避免可能不需要的输出。

答案 1 :(得分:0)

这取决于个人需求,他们希望如何显示错误。 在您的情况下,我建议您使用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.*/
}

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

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