得到一个异常,触发“调用MyClass::jsonSerialize()失败”;例外


Getting an exception that triggered "Failed calling MyClass::jsonSerialize()" exception

这个例子:

<?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,这是这个错误的真正原因?

答案在Exception类的previous属性中。为了得到原始的异常,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;
    }
}