【发布时间】:2010-12-21 00:46:08
【问题描述】:
如果你在 PHP 中使用custom error handler,你可以看到一个错误的上下文(所有变量在它发生的地方的值)。有什么办法可以解决例外情况吗?我的意思是获取上下文,而不是设置异常处理程序。
【问题讨论】:
标签: php exception error-handling
如果你在 PHP 中使用custom error handler,你可以看到一个错误的上下文(所有变量在它发生的地方的值)。有什么办法可以解决例外情况吗?我的意思是获取上下文,而不是设置异常处理程序。
【问题讨论】:
标签: php exception error-handling
您可以手动将上下文附加到您的异常。我从未尝试过,但是创建一个在构造函数中调用并保存get_defined_vars() 以供以后检索的自定义异常会很有趣。
这将是一个严重的例外:-)
概念证明:
class MyException extends Exception() {
protected $throwState;
function __construct() {
$this->throwState = get_defined_vars();
parent::__construct();
}
function getState() {
return $this->throwState;
}
}
更好:
class MyException extends Exception implements IStatefullException() {
protected $throwState;
function __construct() {
$this->throwState = get_defined_vars();
parent::__construct();
}
function getState() {
return $this->throwState;
}
function setState($state) {
$this->throwState = $state;
return $this;
}
}
interface IStatefullException { function getState();
function setState(array $state); }
$exception = new MyException();
throw $exception->setState(get_defined_vars());
【讨论】:
Exception 不可见,则不会。为了克服这个问题,我建议添加一个方法setState(array $state) 并在抛出异常时提供get_defined_vars。我相应地更改了代码。
setState()是一个坏主意;)PS:这就是它的完成方式in Symfony(免责声明:我写了它)跨度>
难道你也不能这样做:
class ContextException extends Exception {
public $context;
public function __construct($message = null, $code = 0, Exception $previous = null, $context=null) {
parent::__construct($message, $code, $previous);
$this->context = $context;
}
public function getContext() {
return $this->context;
}
}
这将避免需要实例化异常然后抛出它。
【讨论】:
PHP 中的异常:
http://www.php.net/manual/en/language.exceptions.extending.php
基本异常类的方法:
final public function getMessage(); // message of exception
final public function getCode(); // code of exception
final public function getFile(); // source filename
final public function getLine(); // source line
final public function getTrace(); // an array of the backtrace()
final public function getPrevious(); // previous exception
final public function getTraceAsString(); // formatted string of trace
所以,如果你发现了一个基本的异常,这就是你必须处理的。如果您无法控制生成异常的代码,那么获取更多上下文就没有什么可做的了,因为当您捕获它时,抛出异常的上下文已经消失了。如果您自己生成异常,那么您可以在引发异常之前将上下文附加到异常。
【讨论】: