如何扩展 PDO例外


How to extend PDOexception?

我写:

class MyPDOException extends PDOException{
    protected $_errorMsg;
    public function getErrorMsg(){
        $this->_errorMsg  =
                'Error: ' . $this->getMessage() . '<br />' .
                'File: ' . $this->getFile() . '<br />' .
                'Line: ' . $this->getLine(). '<br/>';
        return $this->_errorMsg;
    }
}

然后:

class DB{
    protected $_db;
    const DB_HOST = 'localhost';
    const DB_NAME = 'ws';
    const DB_USER = 'root';
    const DB_PASSWORD = 'homedb';
    public function __construct(){
        try{
            $this->_db = new PDO("mysql:host=" . self::DB_HOST . 
            ";dbname=" . self::DB_NAME, self::DB_USER , self::DB_PASSWORD);
            $this->_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        catch (MyPDOException $e){
            $e->getErrorMsg();
        }
    }
    ...

例如,如果密码不正确,我会收到:

致命错误:未捕获的异常"PDOException",并显示消息 'SQLSTATE[HY000] [1045] 访问被拒绝...

我做错了什么?

您正确扩展了异常,但这并不能确保使用不同异常的代码现在正在使用您的自定义异常,只是因为您扩展了它。PDO类总是会抛出PDOException,仅仅是因为代码指示PHP这样做。

<?php
class PDOException extends 'Exception {}
class PDO {
    public function __construct() {
        // code ...
        // code ...
        if ($error) {
            throw new 'PDOException();
        }
    }
}
class MyPDOException extends 'PDOException {}

正如你清楚地看到的,PDO类永远不会抛出MyPDOException,因为它使用的是PDOException(硬编码)。当然,您可以通过执行以下操作来解决此问题:

<?php
class MyPDO extends 'PDO {
    public function __construct() {
        try {
            parent::__construct();
        } catch ('PDOException $e) {
            throw new 'MyPDOException($e->getMessage(), (int) $e->getCode(), $e);
        }
    }
 }

但是,如果您除了将异常转换为另一个异常之外没有执行任何其他操作,则这根本没有意义。


这是非常基本的东西。考虑阅读一本关于用PHP或任何其他面向对象编程语言学习面向对象编程的书或网站。