【问题标题】:Throw custom exception PDO抛出自定义异常 PDO
【发布时间】:2026-01-08 09:05:01
【问题描述】:

有没有办法设置一个 Pdo 对象来抛出一个自定义异常而不是默认的 PDOException?

例如:

class MyCustomDbException extends PDOException{}

$pdo = new Pdo("mysql:host=localhost;dbname=myapp", "user_name", "secret_password");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EXCEPTION_CLASS, "MyCustomDbException");

【问题讨论】:

    标签: php exception pdo custom-exceptions


    【解决方案1】:
    try {
        // Code is here
    } catch (PDOException $e) {
        // See exception manual if you want to path through message or anything else from pdo exception.
        throw new YourException('PDO exception was thrown');
    }
    

    http://php.net/manual/en/language.exceptions.extending.php 看看如何通过参数进行路径。

    【讨论】:

    • 相当简单。谢谢!