如果数据库相关内容是可选的,如何显示错误并加载页面的其余部分



My.php包括quote.php和页面的其余部分。当连接失败时,我看到以下错误,页面的其余部分没有加载:

致命错误:未捕获的mysqli_sql_exception:-----include_one('C:\examplep\htdocs…'(----

请考虑此处引用的数据库在另一个教室中,并且它们的优先级有时要求它们排除访问权限。我们不想依赖它。

我必须做些什么才能显示错误消息,然后继续加载页面的其余部分?

无论您的网站上有什么功能是可选的,都可以使用相同的方法。它不是数据库连接特有的。它也可以是一个你想要curl的网站,而该网站是离线的。

这种技术被称为异常处理。它在大多数高级语言中都非常相似。代码的一部分(可选部分(照常执行任务,如果无法执行任务,则抛出异常。然后,应用程序的核心负责捕获异常并从中恢复,或者正常退出。

PHP(在最新版本中(在数据库连接无法打开时默认抛出异常。你不需要在那里做任何额外的事情。无论您从何处调用可选功能,都可以将其封装在try-catch中,并根据需要从中恢复。例如:

try {
getQuoteFromDB();
} catch(mysqli_sql_exception|PDOException) { // use whichever exception you need, not both
// Log the error and display different part of the site
}

当你自己设计可选部件时,如果你想抛出异常,只需执行:

if (/* something cannot be done */) {
throw new Exception('Something cannot be done');
}

通过捕获异常并重新生成自定义异常,从quote.php文件中的底层DB扩展抽象出来可能是个好主意。

当使用try-catch是合理的时,您的情况是罕见的。

你所需要做的就是把include包装在一个try-catch中:

try {
require 'quote.php';
} catch(Throwable $e) {
error_log($e); // for the future inspection
echo "Problem loading this part of page";
}

仅此而已。将显示错误消息,并加载页面的其余部分。

当然,只有当quote.php中的内容是可选的时,才应该使用这种方法。在其他所有情况下,必须没有本地try-catch,而是有一个站点范围的错误处理程序。

php/msqli正在抛出异常。您需要在程序中编写异常处理程序代码(try { } catch (mysqli_sql_exception $e) { }代码(来处理错误。

作为代码当前状态的快速而肮脏的工作组,您可以将这行代码放在页面顶部。给这行代码

mysqli_report(MYSQLI_REPORT_OFF):;

这将抑制php异常和警告,并让您完全依赖mysqli_connect_errno()来捕获错误。

使用@O。琼斯的想法和一些讨厌的GoTO,这就完成了任务。警告和错误仍然显示。页面的其余部分现在可以加载了。

<?php
mysqli_report(MYSQLI_REPORT_OFF);
$dbServer =   "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName =     "project_01";
$conn = mysqli_connect($dbServer, $dbUsername, $dbPassword, $dbName);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to the MySQL Database: ";
goto end;
}
$sql = "SELECT * FROM  tbl_quotes";
if ($result=mysqli_query($conn,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
$rand = random_int(1,$rowcount);
} else {
echo "No records were found";
goto end;
}
$sql = "SELECT quote, credit FROM  tbl_quotes where ID = $rand";
if ($result = mysqli_query($conn, $sql)) {
// Fetch one and one row
while ($row = mysqli_fetch_row($result)) {
printf ("%s" . " - " . "(%s)n", $row[0], $row[1]);
}
// Free result set
mysqli_free_result($result);
}
end:
?>

感谢所有看过的人。

相关内容

最新更新