这个例子:
<?php
class MyCustomException extends Exception {
}
class MyClass implements JsonSerializable {
function jsonSerialize()
{
throw new MyCustomException('For some reason, something fails here');
}
}
try {
json_encode(new MyClass);
} catch(Exception $e) {
print $e->getMessage() . "\n";
}
将输出:调用 MyClass::jsonSerialize() 失败
。如何得到MyCustomException
,这就是这个错误的真正原因?
最佳答案
答案在 Exception
类的 previous
属性中。要获得原始异常,try - catch
block 应该稍微改变一下:
try {
json_encode(new MyClass);
} catch (Exception $e) {
if ($e->getPrevious()) {
print $e->getPrevious()->getMessage() . "\n";
} else {
print $e->getMessage() . "\n";
}
}
这个异常也可以重新抛出:
try {
json_encode(new MyClass);
} catch (Exception $e) {
if ($e->getPrevious()) {
throw $e->getPrevious();
} else {
throw $e;
}
}
关于php - 获取触发 "Failed calling MyClass::jsonSerialize()"异常的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25155500/