错误“未捕获的 PDOException”,即使我使用 try-catch

KMK*_*KMK 3 php mysql pdo

我正在使用 PDO 连接到 mySQL 数据库。当登录错误时,即使我使用了 try-catch,它也会给出完整的错误堆栈跟踪。

try
{
    $this->db = new PDO("mysql:host='host' dbname='db' charset=utf8", $username, $password);        

    // Tried both with and without these attributes
    $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $e)
{
    echo "Database connection error: " . $e->getMessage());
    exit;
}
Run Code Online (Sandbox Code Playgroud)

运行此代码时 - 使用不存在的数据库名称 - 我收到以下错误:

致命错误:未捕获的 PDOException:SQLSTATE[HY000] [1044] 用户“user”对数据库“db”的访问被拒绝.....

它打印出所有信息。如果登录时出现错误,我只希望代码退出并将消息写入日志文件。

为什么catch没有捕捉到这个异常?

我在我的 Windows 计算机上使用本地 Apache 服务器。也许这是由一些错误配置引起的?

任何帮助表示赞赏。

h2o*_*ooo 7

您收到此错误是因为您在命名空间中运行代码。

取以下代码:

<?php

namespace foo\bar;

// This PDOException has the full class name \foo\bar\PDOException 
// because it's created in a namespace
class PDOException extends \Exception {} // Just so PHP won't throw an error

$exception1 = new PDOException('foo'); // Referencing the local namespace (foo\bar)
$exception2 = new \PDOException('foo'); // Referencing the global namespace
//                ^ -- The backslash means we are refering to the global namespace

var_dump(get_class($exception1)); // string(20) "foo\bar\PDOException" - local scope
var_dump(get_class($exception2)); // string(12) "PDOException" - global scope
Run Code Online (Sandbox Code Playgroud)

演示

正如你所看到的,如果我们一个命名空间内并且没有在我们的全局类前面加上反斜杠,它会自动假设你引用的类是同一命名空间下的子类。

解决方案

因此,您需要使用\PDOException而不是PDOException. 这样它就知道查看类的全局范围而不是当前的命名空间。