Bar*_*lom 5 php error-handling exception
如果在PHP中使用自定义错误处理程序,则可以查看错误的上下文(所有变量在其发生位置的值).有没有办法为例外做这件事?我的意思是获取上下文,而不是设置异常处理程序.
您可以手动将上下文附加到您的异常.我从来没有尝试过,但是在构造函数中调用并保存get_defined_vars()以供以后检索的自定义异常会很有趣.
这将是一个重要的例外:-)
概念证明:
class MyException extends Exception() {
protected $throwState;
function __construct() {
$this->throwState = get_defined_vars();
parent::__construct();
}
function getState() {
return $this->throwState;
}
}
Run Code Online (Sandbox Code Playgroud)
更好的是:
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());
Run Code Online (Sandbox Code Playgroud)
小智 6
难道你也不能这样做:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
这将避免实例化异常然后抛出它的需要。
| 归档时间: |
|
| 查看次数: |
4204 次 |
| 最近记录: |