有没有办法在类的方法中使用自定义异常处理程序,而不是默认异常处理程序__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
}
胡说叔叔
慕莱坞森