这个例子:
<?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";
}
将输出:Failed calling MyClass::jsonSerialize()
。如何获得MyCustomException
,这是导致此错误的真正原因?
答案 0 :(得分:9)
答案在previous
类的Exception
属性中。要获得原始异常,try - catch
块应该稍微改变一下:
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;
}
}