[英]Within a fetch() Promise, how to .catch server errors messages when status is 4xx or 5xx?
In a locally run Node.js script, this works when status is 200:在本地运行的 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());
But the fetch
also works without triggering the .catch
logic when the response status is 4xx or 5xx (see for example this answer ).但是,当响应状态为 4xx 或 5xx 时,
fetch
也可以在不触发.catch
逻辑的情况下工作(例如,请参见此答案)。
Execution doesn't break and I actually receive an error message when the function is called as if that would be the correct, normal result - as the output of response.json()
.执行不会中断,当调用 function 时,我实际上会收到一条错误消息,就好像那将是正确的正常结果一样 - 正如
response.json()
的 output 一样。
This message is in plain English, something like "error: 'Incorrect path. Please check https://www.somesite.com/api/'" .此消息是简单的英语,类似于“错误:'路径不正确。请检查https://www.somesite.com/api/'” 。
I would like to preserve/display this error message, only I would like to catch it within the function getJSON
in the module file, instead of having to wrap some logic around it at the destination, potentially repeating the same code multiple times everywhere the function is called, instead of dealing with the issue just once at the source.我想保留/显示此错误消息,只是我想在模块文件中的 function
getJSON
中捕获它,而不必在目的地围绕它包装一些逻辑,可能会在 function 的任何地方重复相同的代码多次被调用,而不是只在源头处理一次问题。
So I modified the .then
clause like this, which also works:所以我像这样修改了
.then
子句,它也有效:
.then(response => { if (response.ok) { // .ok should be status 200 only, I suppose
return response.json();
} else { throw new Error(response.status) }
This now triggers the .catch
clause as intended, displaying "Error: 404 [etc]".现在这会按预期触发
.catch
子句,显示“错误:404 [等]”。 Except what I would like to throw is the original error message "Incorrect path [etc]" and that I could not do.除了我想抛出的是原始错误消息“不正确的路径[等]”而且我做不到。 I tried
我试过了
.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]
I guess I need to resolve the response.json()
promise as if all was ok, but how to do that?我想我需要解决
response.json()
promise 好像一切都好,但是该怎么做呢?
I also had a look at the request
object with console.dir(request, { depth: null })
to see if I could extract the error message from there, but I couldn't find it and the object still contained many unexpanded elements like [Function: onerror]
or [Function: onclose]
for example.我还查看了带有
console.dir(request, { depth: null })
的request
object 以查看是否可以从那里提取错误消息,但我找不到它,并且 ZA8CFDE6331BD59EB2666F891111C4 之类的元素仍然包含许多 unexpandedB例如[Function: onerror]
或[Function: onclose]
。
Try response.text()
instead of response.json()
when the status code is 400
or 500
.当状态码为
400
或500
时,尝试response.text()
而不是response.json()
。 In my experience, the error messages are typically returned by the text
callback.根据我的经验,错误消息通常由
text
回调返回。
See this answer to a similar question.请参阅此对类似问题的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.