【问题标题】:async function returning UnhandledPromiseRejectionWarning with try/catch (axios)异步函数返回 UnhandledPromiseRejectionWarning 与 try/catch (axios)
【发布时间】:2021-07-13 21:09:34
【问题描述】:

对于具有 try/catch 块的异步函数,我收到了 UnhandledPromiseRejectionWarning。我错过了什么?

// In local module http.js
async function get(url, callback) {
    try {
        const response = await axios.get(url)
        if (callback) {
            callback(null, response.data)
        }
    } catch (err) {
        console.error("GET failed to "+url+" - "+err);
        callback(err)
    }
}

我这样调用函数。我没有在这里使用 await,因为我希望得到回调的结果:

http.get(config.hostController+"/v0/portal/subscribers/"+req.session.subscriberId, function(err, response){
    if (err) {
        return res.status(err).send(response)
    }
    return res.send(response)
})

我遇到了问题,因为我看到了“GET failed to”消息。 (我期待一个 404 错误)。但我仍然收到此错误:

GET failed to http://localhost:7991/v0/portal/subscribers/SUB-b4ae-2ed6 - Error: Request failed with status code 404
(node:23948) UnhandledPromiseRejectionWarning: RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: Error: Request failed with status code 404
    at createError (/Users/sjohnson/github/netreach/netreach-portal/node_modules/axios/lib/core/createError.js:16:15)
    at settle (/Users/sjohnson/github/netreach/netreach-portal/node_modules/axios/lib/core/settle.js:17:12)
    at IncomingMessage.handleStreamEnd (/Users/sjohnson/github/netreach/netreach-portal/node_modules/axios/lib/adapters/http.js:260:11)
    at IncomingMessage.emit (events.js:327:22)
    at endReadableNT (internal/streams/readable.js:1327:12)
    at processTicksAndRejections (internal/process/task_queues.js:80:21) {
  config: [Object],
  request: [ClientRequest],
  response: [Object],
  isAxiosError: true,
  toJSON: [Function: toJSON]
}

【问题讨论】:

    标签: node.js async-await axios try-catch


    【解决方案1】:

    这不是一个混合异步函数和回调的好习惯,你应该只使用异步等待方法。这是因为抛出错误的范围很广,这可能会导致未处理的 Promise 拒绝错误

    你有 2 个选项来实现它,如下所示,仅使用 async/await:

    // option 1 that 'get' don't throw the error but always return
    async function get(url) {
      try {
        const response = await axios.get(url);
        return { data: response.data };
      } catch (error) {
        console.error(`GET failed to ${url} - ${error}`);
        return { error };
      }
    }
    
    async function controller(res) {
      const result = await http.get(`${config.hostController}/v0/portal/subscribers/${req.session.subscriberId}`);
      if (result.error) {
        // u can take the status from the error or come up with your own
        return res.status(500).send({ error: result.error });
      }
      return res.send(result.data);
    }
    
    
    // option 2 that 'get' throw the error
    async function get(url) {
      const response = await axios.get(url);
      return response.data;
    }
    
    async function controller(res) {
      try {
        const result = await http.get(`${config.hostController}/v0/portal/subscribers/${req.session.subscriberId}`);
        return res.send(result);
      } catch (error) {
        // u can take the status from the error or come up with your own
        return res.status(500).send({ error });
      }
    }
    

    【讨论】:

      【解决方案2】:

      事实证明,该异常是次要错误。当我返回一个错误callback(err) 时,我正在返回一个字符串。然后我尝试使用err 作为http 状态码。返回 err.response.status 反而解决了问题。

      【讨论】:

        猜你喜欢
        • 2021-11-27
        • 2011-09-16
        • 1970-01-01
        • 1970-01-01
        • 2020-01-02
        • 1970-01-01
        • 2019-11-11
        • 2018-05-23
        • 2011-11-04
        相关资源
        最近更新 更多