代码之家  ›  专栏  ›  技术社区  ›  user2066480

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

  •  0
  • user2066480  · 技术社区  · 4 年前

    在本地运行的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());
    

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

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

    这条消息是纯英文的,类似于“error:'路径不正确。请检查 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) }
    

    这现在触发 接住 子句,显示“错误: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() 保证好像一切都好,但怎么做呢?

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

    1 回复  |  直到 4 年前
        1
  •  2
  •   Christian Lisle    4 年前

    尝试 response.text() 而不是 response.json() 当状态代码为 400 或 500 。 根据我的经验,错误消息通常由 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);
    });