You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JSON.parse报错后返回响应为空对象问题排查求助

问题排查:JSON解析错误返回空对象的原因及解决办法

核心原因

当JSON.parse()抛出错误时,直接把Error对象传给res.json()会返回空对象,本质原因是:

  • Express的res.json()底层依赖JSON.stringify(),而Error对象的核心属性(比如message、stack)默认是不可枚举的,JSON.stringify()只会序列化可枚举属性,所以最终返回空对象。
  • 控制台能正常打印错误,是因为console.log()会特殊处理Error对象,强制显示其所有信息,不受枚举性限制。

解决方案

需要手动提取Error对象的可序列化属性,再返回给客户端。以下是几种可行方式:

1. 直接提取关键属性

这是最直观的方式,按需返回错误信息,生产环境可隐藏堆栈信息避免泄露:

catch (error) {
  console.log(error);
  res.status(500).json({ 
    error: error.message,
    stack: process.env.NODE_ENV === 'development' ? error.stack : undefined
  });
}

2. 将Error转为普通对象

用Object.assign()把Error对象转成普通对象,确保所有属性被序列化:

catch (error) {
  console.log(error);
  const errorObj = Object.assign({}, error, {
    message: error.message,
    stack: error.stack
  });
  res.status(500).json({ error: errorObj });
}

3. 修正测试代码的JSON语法错误

你的最小复现示例中,测试用的JSON字符串存在语法错误:'{\"name: \"John\"}'应该改为'{\"name\": \"John\"}'(或直接'{"name": "John"}',单引号包裹无需转义),否则会始终触发解析错误。修正后的完整测试代码:

const express = require("express");

const server = express();

const customParser = (req, res, next) => {
  try {
    const testData = '{"name": "John"}';
    req.body = JSON.parse(testData);
    next();
  } catch (error) {
    console.log(error);
    res.status(500).json({ 
      error: error.message,
      stack: process.env.NODE_ENV === 'development' ? error.stack : undefined
    });
  }
};

server.get("/", customParser, (req, res) => {
  res.json({parsedData: req.body});
});

server.listen(3000);

内容的提问来源于stack exchange,提问作者Ashutosh Aswal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 07:36:34