简体   繁体   English

在 fetch() Promise 中,当状态为 4xx 或 5xx 时,如何捕获服务器错误消息?

[英]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 .当状态码为400500时,尝试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.

相关问题 如何将 4XX 和 5XX 错误发送给哨兵? - How to send 4XX and 5XX errors to sentry? 是4xx和5xx.network错误吗? - Is 4xx and 5xx network errors? 可以在控制台中隐藏资源加载的5xx / 4xx错误吗? - Can 5xx/4xx errors for resource loads be hidden in the console? 当存在4xx或5xx Http错误代码时,在Javascript中解析JSONP响应 - Parsing JSONP Response in Javascript when 4xx or 5xx Http Error Code is Present 使用then / catch语法通过axios分别捕获4xx和代码错误 - Catching 4xx and code errors separately with axios using then / catch syntax 4xx 状态代码是否应该被视为前端/SSR 应用程序中的错误? - Should 4xx status codes be considered errors in a Frontend/SSR application? 如何使用 axios 客户端重试 5xx 错误 - How to use axios client to retry on 5xx errors 如何在 fetch api 中处理 HTTP 代码 4xx 响应 - How to handle HTTP code 4xx responses in fetch api 使用 Redux 工具包异步 REST ZDB974238714CA8DE6FZA 模式时如何捕获 HTTP 4xx 错误? - How to trap HTTP 4xx errors when using Redux Toolkit async REST API pattern? javascript响应未解析为状态码4xx - javascript response not parsed with status code 4xx
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM