有没有办法在类的方法中使用自定义异常处理程序,而不是默认异常处理程序__destruct?例如:function myExceptionHandler($e){ echo "custom exception handler"; if(is_object($e) && method_exists($e,'getMessage')) echo $e->getMessage();}set_exception_handler('myExceptionHandler');class MyClass { public function __construct() { // myExceptionHandler handles this exception //throw new Exception("Exception from " . __METHOD__); } public function doStuff() { // myExceptionHandler handles this exception //throw new Exception("Exception from " . __METHOD__); } public function __destruct() { // default exception handler throw new Exception("Exception from " . __METHOD__); }}$myclass = new MyClass();$myclass->doStuff();即使在方法set_exception_handler内调用__destruct,仍使用默认处理程序: public function __destruct() { $callable = function($e) { echo "custom exception handler".PHP_EOL; if(is_object($e) && method_exists($e,'getMessage')) echo $e->getMessage(); }; set_exception_handler($callable); throw new Exception("Exception from " . __METHOD__); // default exception handler }
2 回答
慕莱坞森
TA贡献1810条经验 获得超4个赞
也许是这样的?
<?php
class MyException extends Exception {
public function __construct() {
parent::__construct('my exception');
}
}
class MyClass {
public function __construct()
{
// myExceptionHandler handles this exception
//throw new Exception("Exception from " . __METHOD__);
}
public function doStuff()
{
// myExceptionHandler handles this exception
//throw new Exception("Exception from " . __METHOD__);
}
public function __destruct()
{
// default exception handler
throw new MyException();
}
}
$myclass = new MyClass();
$myclass->doStuff();
- 2 回答
- 0 关注
- 154 浏览
添加回答
举报
0/150
提交
取消