IMO 捕获所有错误的最佳方法和最简单的方法是扩展 mysqli 类:
class DBException extends Exception {
}
class DBConnectException extends DBException {
}
class DBQueryException extends DBException {
}
class DB extends MySQLi {
private static $instance = null;
private function __construct() {
parent::__construct('host',
'username',
'passwd',
'dbname');
if ($this->connect_errno) {
throw new DBConnectException($this->connect_error, $this->connect_errno);
}
}
private function __destructor() {
parent::close();
}
private function __clone() {
}
public static function getInstance() {
if (self::$instance == null) {
self::$instance = new self();
}
return self::$instance;
}
public function query($query, $resultmode = MYSQLI_STORE_RESULT) {
$result = parent::query($query, $resultmode);
if (!$result) {
// or do whatever you wanna do when an error occurs
throw new DBQueryException($this->error, $this->errno);
}
return $result;
}
}