【问题标题】:Within a fetch() Promise, how to .catch server errors messages when status is 4xx or 5xx? [duplicate]在 fetch() Promise 中,当状态为 4xx 或 5xx 时,如何 .catch 服务器错误消息? [复制]
【发布时间】:2022-01-14 20:00:37
【问题描述】:

在本地运行的 Node.js 脚本中,这在状态为 200 时有效:

// module file
import fetch from "node-fetch";
export const getJSON = () => {
  const url = 'https://api.somesite.com/api/v0/etc';
  const options = {method: 'GET', headers: {Accept: 'application/json'}};
  const request = fetch(url, options)
    .then(response => response.json())
    .catch(err => console.log("somesite:", err));
  return Promise.resolve(request);
};

// execution file
import { getJSON } from './libs/api_requests.mjs';
console.log("func call", await getJSON());

但是当响应状态为 4xx 或 5xx 时,fetch 也可以在不触发 .catch 逻辑的情况下工作(例如参见 this answer)。

执行不会中断,当函数被调用时,我实际上会收到一条错误消息,就好像那将是正确的正常结果 - 作为 response.json() 的输出。

这条消息是简单的英文,类似于“错误:'路径不正确。请检查https://www.somesite.com/api/'"

我想保留/显示此错误消息,只是我想在模块文件中的函数getJSON 中捕获它,而不是在目标处围绕它包装一些逻辑,可能会重复相同的代码函数在任何地方被调用多次,而不是在源头处理一次。

所以我像这样修改了.then 子句,它也有效:

.then(response => { if (response.ok) { // .ok should be status 200 only, I suppose
        return response.json();
      } else { throw new Error(response.status) }

现在这会按预期触发.catch 子句,显示“错误:404 [等]”。除了我想抛出的是原始错误消息“不正确的路径 [etc]”和 我做不到。我试过了

.then(response => { if (response.ok) {
      return response.json();
    } else { throw new Error(response.json()) } // somesite: Error: [object Promise]

.then(response => { if (response.ok) {
      return response.json()
    } else { throw new Error(Promise.resolve(response.json())) } // somesite: Error: [object Promise]

.then(response => { if (response.ok) {
      return response.json()
    } else { throw new Error(return response.json()) } // SyntaxError: Unexpected token 'return'

.then(response => { if (response.ok) {
        return response.json();
      } else { throw new Error(Promise.resolve(request)) } // somesite: Error: [object Promise]

我想我需要解决response.json() 的承诺,好像一切正​​常,但该怎么做呢?

我还查看了带有console.dir(request, { depth: null })request 对象,看看我是否可以从那里提取错误消息,但我找不到它并且该对象仍然包含许多未展开的元素,例如[Function: onerror] 或以[Function: onclose] 为例。

【问题讨论】:

  • Return Promise all([response.ok, response.json()]),第二次检查错误.then()

标签: javascript node.js error-handling es6-promise


【解决方案1】:

当状态码为400500 时,尝试response.text() 而不是response.json()。 根据我的经验,错误消息通常由 text 回调返回。


请参阅this answer 来回答类似问题。


编辑:

添加了以下代码,由 OP 建议。

.then((response) => {
  if (response.ok) {
    return response.json();
  }
  else {
     return response.text()
       .then((text) => {
         throw(text);

         // if the error is an object and you just want to display some elements:
         throw(JSON.parse(text));
       });
  }
})
.catch((err) => {
  // in case you want to log the error
  console.log("somesite: ", err));

  return new Error("somesite: " + err);
});

【讨论】:

  • 相同结果:错误:[object Promise]。不过谢谢!
  • 明白了。抱歉,我无法提供更多帮助!
  • 所以你指出的链接stackoverflow.com/a/44576265/2066480的答案实际上解决了这个问题。非常感谢你。只有脚本的执行没有停止。我是否必须在“.catch”子句中再次抛出?
  • 如果您希望脚本因错误而终止,则需要为uncaught。从.catch 中抛出错误应该可以工作。
  • 我现在用.catch(err => {return new Error("somesite:: " + err)}); 停止脚本所以这也是固定的。它不漂亮,但能胜任。
猜你喜欢
  • 2013-06-01
  • 2021-07-06
  • 1970-01-01
  • 2011-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-26
相关资源
最近更新 更多