如何在 JavaScript 异步获取调用中使用返回的 JSON 错误

How to use returned JSON error in a JavaScript async fetch call

我有一个 async fetch 调用调用我的后端来创建一个具有电子邮件地址的客户。如果成功,返回的 JSON 将发送到 doNextThing() 函数。

如果后端 returns 一个非 200 状态代码它也 returns JSON 像 {"message": "Something went wrong"}。我想 catch 错误并将该消息发送到 console.

我已经阅读了数十个略微相似的问题并接近答案。到目前为止,我有以下内容,但是如果后端的响应是 403 状态代码,那么控制台输出 "FORBIDDEN"。我 认为 这是因为承诺尚未解决,因此还没有完整的 JSON 响应。或者其他的东西。但我不知道我错过了什么。

async function createCustomer(email) {
  return fetch("/api/create-customer", {
    method: "post",
    headers: {"Content-Type": "application/json"},
    body: JSON.stringify({email: email})
  })
    .then(function(response) {
      if (response.ok) {
        return response.json();
      } else {
        return Promise.reject({
          status: response.status,
          statusText: response.statusText
        });
      }
    })
    .then(function(returned_data) {
      doNextThing(returned_data);
    })
    .catch(function(e) {
      console.error(e.statusText);
    });
}

如果您使用的版本支持,我个人推荐使用 async/await 语法。它确实简化了代码并允许您轻松使用 try/catch 语法。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await#Browser_compatibility

它似乎在 IE 中不起作用,但如果那是一个交易破坏者。

async function createCustomer(email) {
try {
    const response = await fetch("/api/create-customer", {
        method: "post",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email: email })
    })
    if (response.ok) {
        const returnedData = await response.json();
        // if doNextThing is an async function, you can await it as well or just return it 
        doNextThing(returnedData);
    } else {
        throw {
            json: await response.json()
            status: response.status,
            statusText: response.statusText
        };
    }
} catch (requestErr) {
    // do what you like with the error
    // this will be called if you "throw" above or 
    // if fetch() rejects
    if (requestErr.json){
        console.error(JSON.stringify(requestErr.json));
    }
    console.error("Request err:" + requestErr);
}

}

如果有帮助请告诉我。