【问题标题】:Uncaught (in promise) TypeError: error.json is not a function - while destructing error messageUncaught (in promise) TypeError: error.json is not a function - 同时破坏错误消息
【发布时间】:2020-07-15 07:35:06
【问题描述】:

我正在开发 React Redux 应用程序,

我收到 “Uncaught (in promise) TypeError: error.json is not a function” 错误,同时尝试从返回的 API 错误中破坏错误消息。我的 API 返回错误,结构如下:

{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "|5f13e001-48d7893e3cc8e8ff.",
  "errors": {
    "Code": [
      "'Code' must not be empty."
    ],
    "Name": [
      "'Name' must not be empty."
    ]
  }
}

这是我处理保存方法的方式:

  const handleSave = (event) => {
    event.preventDefault();
    setSaving(true);
    saveTeam(team)
      .then(() => {
        showSnackbar("Team was saved successfully");
        history.push("/teams");
      })
      .catch((error) => {
        let errorMessage = error.message.json();
        debugger;

        setErrors({ onSave: error.message }); //<---- In here I want to pass just the list of errors 
        setSaving(false);
      });
  };

我遇到了这个异常:

Uncaught (in promise) TypeError: error.message.json is not a function

顺便说一句。我将error.message 传递给SetErrors,然后我将其打印在屏幕上。这就是我得到的:

{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"|5f13e004-48d7893e3cc8e8ff.","errors":{"Code":["'Code' must not be empty."],"Name":["'Name' must not be empty."]}}

所以error.message 就是我要找的……但我怎样才能破坏它呢?

【问题讨论】:

  • 如果 errors.message 返回您正在显示的对象 - {"type": ...},那么如果它还不是 JavaScript 对象,您应该使用 JSON.parse,或者只是选择您想要的任何属性错误信息,例如error.title
  • 你能澄清为什么你特别试图在错误时执行 json() 吗?什么给你的印象是它应该有一个 json() 方法?如果你只是 console.log(error) 会发生什么?
  • @AlexanderStaroselsky 我想获取错误列表。 console.log(error.message) 打印一个 json 格式的字符串
  • 好的,如果你 console.log(error.message) 什么会注销?你为什么要执行一个方法 json()?
  • @IshThomas 你试过用JSON.parse(error.message)JSON 变成一个普通的JavaScript 对象,这样你就可以获取你需要的任何属性了吗?

标签: javascript json reactjs redux async-await


【解决方案1】:

假设error.message实际上是JSON,你应该使用JSON.parseJSON字符串解析成JavaScript对象:

const error = {
  message: JSON.stringify({
    type: "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    title: "One or more validation errors occurred.",
    status: 400,
    traceId: "|5f13e004-48d7893e3cc8e8ff.",
    errors: {
      Code: ["'Code' must not be empty."],
      Name: ["'Name' must not be empty."]
    }
  })
};
console.log(error.message);

// use destructing assignment to unpack properties from the object
const { type, title, status } = JSON.parse(error.message);

console.log("");
console.log("type", type);
console.log("title", title);
console.log("status", status);

回到您的代码,它应该如下所示:

const handleSave = event => {
  event.preventDefault();
  setSaving(true);
  saveTeam(team)
    .then(() => {
      showSnackbar("Team was saved successfully");
      history.push("/teams");
    })
    .catch(error => {
      const { errors }  = JSON.parse(error.message);
      let allErrors = [];

      for (const [key, array] of Object.entries(errors)) {
        // use `spread syntax` to combine all error messages
        allErrors = [...allErrors, ...array]
      }
      setErrors({ onSave: allErrors.join(";") });
      // 'Code' must not be empty.;'Name' must not be empty. 

      setSaving(false);
    });
};

参考资料:

【讨论】:

    【解决方案2】:

    您收到错误是因为您的 json 对象没有要调用的 function 类型的属性 你可以像这样解构一个json对象

    var jsonob={
      "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
      "title": "One or more validation errors occurred.",
      "status": 400,
      "traceId": "|5f13e001-48d7893e3cc8e8ff.",
      "errors": {
        "Code": [
          "'Code' must not be empty."
        ],
        "Name": [
          "'Name' must not be empty."
        ]
      }
    }
    
    const {type,title,status,traceId,errors}=jsonob
    console.log(type,title,status,traceId,errors)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-13
      • 2020-03-17
      • 2020-01-06
      • 2021-03-10
      • 2021-09-30
      • 2020-12-22
      • 2019-06-15
      • 2017-07-20
      相关资源
      最近更新 更多