获取触发的异常"调用MyClass失败:: jsonSerialize()"例外

时间:2014-08-06 08:23:33

标签: php json error-handling

这个例子:

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

1 个答案:

答案 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;
    }
}