我只是想知道捕获数据库错误的最佳方法是什么。如果发生错误,我想向用户显示一些“抱歉”的内容,并向技术支持发送电子邮件。
现在,我将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.*/
}
因此,通过这种方式,您可以向用户显示通用消息,并通过电子邮件向开发团队显示详细的错误消息。因此,无论何时发生一些严重的异常或错误,您的团队都会通过电子邮件获得通知。
希望这会帮助某人。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句