Fastify Schema读取嵌套对象报错:无法读取null的name属性
解决Fastify Schema中manager字段引发的运行时错误
问题场景
使用的Fastify Schema如下:
{"response": {"200": {"type": "object","properties": {"data": {"type": "array","items": {"type": "object","properties": {"id": {"type": "string"},"created_at": {"type": "string"},"modified_at": {"type": "string"},"title": {"type": "string","example": "unit #323","description": "the org unit's title"},"parent": {"type": "string","description": "the parent org unit","nullable": true,"example": null},"manager": {"type": "object","properties": {"code": {"type": "string","example": "code#538","description": "employer code"},"name": {"type": "string","example": "John"},"status": {"type": "string","nullable": true,"enum": ["active","inactive"]},"org_unit": {"type": "string","nullable": true}}}}},"next": {"type": "string"},"prev": {"type": "string"}}}},"querystring": {"filter": {"type": "string","description": "a json decoded string of fields to be filtered, or a sql where statement with query.values provided","example": {"title": "value","parent": "value","manager": "value"}}}}
Schema核心结构:
{ id, title, manager: {id, name, code, ....} }
预期响应数据结构:
[ {id, manager: {id, name, ...}} ]
运行时出现如下错误:
Cannot read properties of null (reading 'name') at anonymous3 (eval at build (node_modules/fast-json-stringify/index.js:175:23),
移除Schema中的manager字段后,错误消失。
问题原因
错误指向访问null对象的name属性,说明实际返回的响应数据中,manager字段存在为null的情况,但当前Schema里的manager字段仅定义了type: "object",未设置nullable: true。Fastify依赖的fast-json-stringify会基于Schema生成序列化逻辑,默认认为manager一定是对象,当实际数据为null时,就会触发读取null属性的报错。
解决方案
给Schema中的manager字段添加nullable: true配置,使其匹配实际数据中可能为null的场景:
修改后的manager字段Schema片段:
"manager": { "type": "object", "nullable": true, "properties": { "code": {"type": "string","example": "code#538","description": "employer code"}, "name": {"type": "string","example": "John"}, "status": {"type": "string","nullable": true,"enum": ["active","inactive"]}, "org_unit": {"type": "string","nullable": true} } }
这样fast-json-stringify在序列化时会先判断manager是否为null,为null时不会尝试读取其内部属性,避免报错。
内容的提问来源于stack exchange,提问作者Sherif eldeeb
相关产品推荐
相关产品推荐

