Javascript 获取 api 使用自定义错误消息

Javascript fetch api use custom error message

我正在寻找一种处理本机 javascript 获取 api 错误的方法。曾经使用 jQuery,但我正在尝试使用更多本机 javascript 功能。

我找到了这个博客并且喜欢这种方法:https://learnwithparam.com/blog/how-to-handle-fetch-errors/

fetch(url)
  .then((response) => {
    if (response.status >= 200 && response.status <= 299) {
      return response.json();
    } 

    throw Error(response.statusText);
    
  })
  .then((jsonResponse) => {
    // do whatever you want with the JSON response
  }).catch((error) => {
    // Handle the error
    console.log(error);
  });

但是,在 catch 中,我得到了属于 HTTP 代码的 statusText。例如 400 Bad request。但这不是我想要的,我对服务器的调用将准确地响应错误。所以我想使用响应正文作为错误。我尝试了不同的方法,但如果 HTTP 代码为 400,我无法获得响应正文。对于 jQuery,我使用了 response.responseJSON.html。但这不适用于 fetch api.

那么我怎样才能将响应正文用作错误代码。

The fetch API was designed to work best with async functions。如果你可以使你的外部函数 async,你的代码将变成:

try {
  const response = await fetch(url);
  if (!response.ok) {
    const text = await response.text();
    throw Error(text);
  }
  
  const jsonResponse = await response.json();
  // do whatever you want with the JSON response
    
} catch (error) {
  console.log(error);
}

否则,会变得有点复杂:

fetch(url)
  .then((response) => {
    if (response.ok) {
      return response.json();
    }
    
    return response.text().then((text) => throw Error(text));
  })
  .then((jsonResponse) => {
    // do whatever you want with the JSON response
  }).catch((error) => {
    // Handle the error
    console.log(error);
  });