【问题标题】:Best way to remove the trace information from the PDOException __toString method从 PDOException __toString 方法中删除跟踪信息的最佳方法
【发布时间】:2011-04-21 03:42:09
【问题描述】:

是否可以从 __toString 中删除跟踪元素。

我想要的是这样的。

class DBException extends PDOException
{
public function __toString()
{
    return get_class($this) . " '{$this->getMessage()}' in {$this->getFile()}({$this->getLine()})\n";
}
}

我已经尝试过上述方法,但似乎不起作用。有什么想法吗?

如果我使用下面的 try catch 块作为示例,我仍然可以获得跟踪数据。

try {

// Do something here

}catch(DBException $e) {
    echo $e;

}

我原以为回显 $e 会触发我的 DBException 类中的 __toString 方法。

【问题讨论】:

  • 请解释一下似乎不起作用

标签: php exception pdo


【解决方案1】:

过去,当我想使用 PDO 处理异常时(在这种情况下是为了确保不会向用户显示连接详细信息),我所做的是扩展 PDO 类并简要更改异常处理程序:

class extendedPDO extends PDO
{
    public static function exception_handler(Exception $exception)
    {
        // Output the exception details
        die('<h1>Database connection error<p>' . $exception->getMessage() . '</p>');
    }

    public function __construct($dsn, $username=null, $password=null, $options=array())
    {
        // Temporarily change the PHP exception handler while we . . .
        set_exception_handler(array(__CLASS__, 'exception_handler'));

        // Create PDO
        parent::__construct($dsn, $username, $password, $options);

        // Change the exception handler back to whatever it was before
        restore_exception_handler();
    }
}

【讨论】:

  • 那么这是否意味着您的方法,我会在没有 try catch 块的情况下抛出 PDOExceptions 以确保它们是未捕获的异常?
  • 向最终用户显示 any 错误信息有什么意义?只需显示一个典型的“应用程序错误。请重试(稍后)”。消息并将实际错误保存到日志文件中。
  • 这些只是示例,我的项目会记录所有错误并向最终用户显示一条通用消息,就像您建议的那样
  • @Crozin 在开发过程中错误消息可能很有用;)
  • Shawn,这是取自一个特定示例,我想确保使用该类的任何人都无法通过忘记尝试捕获来显示连接详细信息,但我想您可以停止恢复并查看你怎么过。虽然我认为这是不好的做法。
【解决方案2】:

这样的?

public function __toString() {
    $return = "Class: ".get_class($this)
             ."\nMessage: ".$this->getMessage()
             ."\nFile: ".$this->getFile()
             ."\nLine: ".$this->getLine()."\n";
    return $return;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-17
    • 1970-01-01
    • 2010-10-18
    • 1970-01-01
    • 1970-01-01
    • 2019-01-23
    相关资源
    最近更新 更多