【发布时间】: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