我正在尝试使用phpunit来测试连接,我已经创建error_reporting(0)
并分配PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT
,但是当我故意提供错误信息时,它总是转储错误消息,例如,如果我提供错误的帐户,显示
PDOException: SQLSTATE[HY000] [1045] Access denied for user 'test'@'localhost' (us
ing password: YES)
如何关闭它?
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_PERSISTENT => false,
);
$dsn = 'mysql:host=' . $config['host'] . ';dbname=' . $config['database'] . ';charset=utf8';
try {
$this->dbh = new PDO($dsn, $config['username'], $config['password'], $options);
} catch (PDOExeception $e) {
// Do something
}
答案 0 :(得分:1)
PDO::__construct
将始终抛出PDOException
。你无能为力。任何理智的应用程序如果连接失败就应该抛出异常,或者你有充分的理由解释为什么你需要关闭连接上的异常。
除了连接它将适用于其他事务。
示例:强>
<?php
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT,
PDO::ATTR_PERSISTENT => false,
);
$dsn = 'mysql:host=' . $config['host'] . ';dbname=' . $config['database'] . ';charset=utf8';
try {
//THIS WILL THROW EXECPTION IF FAILED, NO MATTER WHAT ERROR MODE YOU SET
$this->dbh = new PDO($dsn, $config['username'], $config['password'], $options);
} catch (PDOException $e) {
// Do something
}
//JUST SILENT THIS WILL NOT CAUSE EXCEPTION
$dbh->query("SELECT badColumn FROM wrongTable");
?>