gpt4 book ai didi

php - PDOException 没有被捕获?

转载 作者:行者123 更新时间:2023-11-29 21:25:34 34 4
gpt4 key购买 nike

我在 PHP 中收到以下错误:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [2003] Can't connect to MySQL server on 'localhost' (10061)' in C:\xampp\htdocs\project\Service\Database.class.php:26 Stack trace: #0 C:\xampp\htdocs\project\Service\Database.class.php(26): PDO->__construct('mysql:host=loca...', 'root', '', Array) #1 C:\xampp\htdocs\project\Service\Database.class.php(54): Service\Database::initialize() #2 C:\xampp\htdocs\project\index.php(15): Service\Database::getHandler() #3 {main} thrown in C:\xampp\htdocs\project\Service\Database.class.php on line 26

错误本身不是问题,我故意终止了MySQL Windows 中的服务来查看发生了什么(我正在使用 XAMPP )。问题是我无法捕获 PDO 的异常对象抛出异常,我不知道为什么。

try {
$host = "localhost";
$dbname = "project";
$userName = "root";
$password = "";
$charset = "utf8";
$dsn = "mysql:host=$host;dbname=$dbname;charset=$charset";

$driverOptions = array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES $charset"
);

// This is the line that supposedly throws the exception (LINE 26):
$dbh = new PDO($dsn, $userName, $password, $driverOptions);

$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

self::setHandler($dbh);
} catch (PDOException $e) {
die("CATCHED"); // This line is never reached
} catch (Exception $e) {
die("CATCHED"); // nor this one.
}

我在这里缺少什么?

最佳答案

我唯一能想到的是,如果您位于命名空间类中,则应该使用 \PDOException 而不是 PDOException

关于php - PDOException 没有被捕获?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35524753/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com