未捕获(承诺)TypeError:error.json不是函数-销毁错误消息时

时间:2020-07-14 22:46:49

标签: javascript json reactjs redux async-await

我正在使用React Redux应用程序

我正在尝试从返回API错误中破坏错误消息时,出现“未捕获(承诺)TypeError:error.json不是函数” 错误。我的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是我想要的...但是我怎么破坏它?

2 个答案:

答案 0 :(得分:1)

您将收到错误消息,因为仅您的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)

答案 1 :(得分: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);
    });
};

参考: