我目前正在尝试为以下情况编写错误处理。我希望能够在数据库为 --read-only
并尝试写入时捕获错误。
WordPress database error INSERT command denied to user 'readonly'@
抛出此错误是因为数据库是--read-only
并且正在尝试写入数据库。但是,这个错误应该已经被我的catch
条件捕获了。
function drools_request($data, $uid) {
try {
$db = _get_db();
$db->insert("requests", [
"uid" => $uid,
"data" => json_encode($data),
]);
}
catch(Error $e){
echo 'Error writing to database: ', $e->getMessage(), "\n";
}
}
正如您从上面的代码片段中看到的那样,$db->insert(
方法正确地中断了,因为它试图写入 $db
实例,即 - -只读
。但是,catch(Error $e)
没有工作,为什么?
这是完整的类(class):
<?php
namespace StatCollector;
function drools_request($data, $uid) {
try {
$db = _get_db();
$db->insert("requests", [
"uid" => $uid,
"data" => json_encode($data),
]);
}
catch(Exception $e)
{
echo 'Error writing to database: ', $e->getMessage(), "\n";
}
}
function drools_response($response, $uid) {
try {
$db = _get_db();
$db->insert("responses", [
"uid" => $uid,
"data" => json_encode($response),
]);
}
catch(Exception $e)
{
echo 'Error writing to database: ', $e->getMessage(), "\n";
}
}
function results_sent($type, $to, $uid, $url = null, $message = null) {
try {
$db = _get_db();
$db->insert("messages", [
"uid" => $uid,
"msg_type" => strtolower($type),
"address" => $to,
"url" => $url,
"message" => $message
]);
}
catch(Exception $e)
{
echo 'Error writing to database: ', $e->getMessage(), "\n";
}
}
function peu_data($staff, $client, $uid) {
try {
if (empty($uid)) {
return;
}
$db = _get_db();
if (! empty($staff)) {
$db->insert("peu_staff", [
"uid" => $uid,
"data" => json_encode($staff)
]);
}
if (! empty($client)) {
$db->insert("peu_client", [
"uid" => $uid,
"data" => json_encode($client)
]);
}
}
catch(Exception $e)
{
echo 'Error writing to databse: ', $e->getMessage(), "\n";
}
}
function response_update() {
$uid = $_POST['GUID'];
$url = $_POST['url'];
$programs = $_POST['programs'];
if (empty($uid) || empty($url) || empty($programs)) {
wp_send_json(["status" => "fail","message" => "missing values"]);
return wp_die();
}
try {
$db = _get_db();
$db->insert("response_update", [
"uid" => $uid,
"url" => $url,
"program_codes" => $programs
]);
wp_send_json(["status" => "ok"]);
wp_die();
}
catch(Exception $e)
{
echo 'Error writing to database: ', $e->getMessage(), "\n";
}
}
为什么 try
和 catch
不起作用?我能做些什么来解决这个问题?这篇文章没有用。
PHP try/catch and fatal error
最佳答案
您的代码位于自定义命名空间中:
namespace StatCollector;
所以这段代码:
catch (Exception $ex)
正在寻找 \StatCollector\Exception
的异常类,这不是抛出的:\Exception
是。
由于 Error
和 Exception
类位于 root 命名空间中,您需要执行以下操作:
catch (\Exception $ex)
和/或:
catch (\Error $ex)
或者只是:
catch (\Throwable $t)
然后也关注Bill Karwin's以上建议。
关于PHP & 可湿性粉剂 : try catch not working when error from DB is thrown,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58018514/