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

JavaScript用includes方法检测响应对象message错误码失效如何处理?

问题点
  • 核心错误:data是res.json()解析完成的JS对象,直接调用toString()只会返回固定值[object Object],不可能包含错误码1121,判断条件永远不触发。
  • 逻辑缺陷:直接模糊匹配字符串的方式容易出现误判,若其他字段也出现1121字符会触发错误逻辑,可靠性差。
修复方案

推荐直接解析嵌套的JSON结构拿到准确的错误码判断,你返回的响应里error字段本身就是标准错误JSON字符串,无需处理多余前缀,解析成本最低:

const data = await res.json();
if (data.statusCode === 400) {
  // 解析error字段的JSON字符串拿到错误对象
  const errorInfo = JSON.parse(data.error);
  if (errorInfo.code === -1121) {
    statusMessage.className = 'alert alert-danger text-center err-message';
    // 直接用返回的msg内容,不用硬编码文案更灵活
    statusMessage.innerHTML = errorInfo.msg;
  }
}

如果需要从message字段提取错误信息,需要先处理掉外层的冗余前缀和引号:

const data = await res.json();
if (data.statusCode === 400) {
  // 提取message中的JSON部分
  const errorJsonStr = data.message.slice(6, -1).replaceAll('\\"', '"');
  const errorInfo = JSON.parse(errorJsonStr);
  if (errorInfo.code === -1121) {
    statusMessage.className = 'alert alert-danger text-center err-message';
    statusMessage.innerHTML = errorInfo.msg;
  }
}
临时调试方案

如果仅需要快速验证功能,也可以直接判断message字段是否包含目标字符,不推荐线上使用:

const data = await res.json();
if (data.statusCode === 400 && data.message.includes('1121')) {
  statusMessage.className = 'alert alert-danger text-center err-message';
  statusMessage.innerHTML = 'Invalid symbol.';
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 16:36:07