【问题标题】:Error "Uncaught PDOException", even though I use try-catch错误“未捕获的 PDOException”,即使我使用 try-catch
【发布时间】:2017-08-09 07:40:17
【问题描述】:

我正在使用 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;
}

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

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

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

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

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

感谢任何帮助。

【问题讨论】:

  • 您是否在命名空间中运行此代码?也许尝试在 PDOException (\PDOException) 前面添加一个后松弛来告诉它使用根命名空间?如果您不这样做,它将搜索您当前的命名空间(例如KMK\apps\PDOException
  • 谢谢@h2ooooooo。代码位于命名空间中。如果您将其写为答案,我会将其标记为正确的

标签: php mysql pdo


【解决方案1】:

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

取以下代码:

<?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

DEMO

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

解决方案

因此您需要使用\PDOException 而不是PDOException。这样它就知道在类的 global 范围内而不是在您当前的命名空间中查找。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-05
    • 2020-09-07
    • 2016-05-21
    • 2014-03-04
    • 2021-10-08
    • 2013-07-18
    • 2011-02-15
    • 1970-01-01
    相关资源
    最近更新 更多