php - 获取触发 "Failed calling MyClass::jsonSerialize()"异常的异常

标签 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";
    }

将输出:调用 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/

相关文章:

javascript - Ember 模型与使用 REST 作为 JSON 接收的数据 Hook

c# - 如何修复错误 : "Could not find schema information for the attribute/element" by creating schema

swift - “ fatal error :在展开可选值时意外发现nil”是什么意思?

php - 为什么从浏览器启动的 php 脚本只执行一个?

php - 比较 MySQL 数据库中的日期

python - Flask Python REST API 在接收 POST 时设置可选 JSON 参数

c# - Newtonsoft 与 IDynamicMetaObjectProvider 实现反序列化类相关的问题

php - 提交时出现PHP错误

php - 如何选择所有表格的行?

php - 需要帮助在 PHP 中重构全局变量