获得UnhandledPromiseRejectionWarning尽管有几个`try`-`catch`块

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了获得UnhandledPromiseRejectionWarning尽管有几个`try`-`catch`块相关的知识,希望对你有一定的参考价值。

我正在使用包含其API的第三方模块。我有以下代码:

const api = require('3rdpartyapi');

 async function callAPI(params) {
  try {
    let result = await api.call(params);
    return result;
  }
  catch(err) {
    throw err;  //will handle in other function
  }
 }
 
 async function doSomething() {
  try {
    //...do stuff
    let result = await callAPI({a:2,b:7});
    console.log(result);
  }
  catch(err) {
    console.error('oh no!', err);
  }
}

尽管try-catch块,第三方API,当它失去与homebase的连接时(经常发生:()),爆炸:

(node:13128) UnhandledPromiseRejectionWarning: FetchError: request to https://www.example.com failed, reason: getaddrinfo ENOTFOUND

其次是:

UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)

怎么没有我的try-catch抓住这个?究竟什么是未处理的,以及如何实际处理这个问题?

答案

重点是等待只将“第一层”拒绝转换为错误,但是承诺内部可能有承诺,并且它们的库可能无法捕获内部的拒绝。我做了一个概念证明3rdpartyapi,可以触发你看到的行为:


(async function () {

// mock 3rdpartyapi
var api = {
    call: async function(){
        await new Promise((resolve, reject) => {
            // why wrap a promise here? but i don't know
            new Promise((innerResolve, innerReject) => {
                innerReject('very sad'); // unfortunately this inner promise fail
                reject('this sadness can bubble up');
            })
        })
    }
};

// your original code
async function callAPI(params) {
    try {
        let result = await api.call(params);
        return result;
    } catch (err) {
        throw err; //will handle in other function
    }
}

async function doSomething() {
    try {
        //...do stuff
        let result = await callAPI({
            a: 2,
            b: 7
        });
        console.log(result);
    } catch (err) {
        console.error('oh no!', err);
    }
}

doSomething();

})();

输出:

$ node start.js
oh no! this sadness can bubble up
(node:17688) UnhandledPromiseRejectionWarning: very sad
(node:17688) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:17688) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

以上是关于获得UnhandledPromiseRejectionWarning尽管有几个`try`-`catch`块的主要内容,如果未能解决你的问题,请参考以下文章

《QQ宠物》全部称号都有哪些,怎么获得?

SpringMVC 获得请求数据 -- 获得Servlet相关API获得请求头(@RequestHeader@CookieValue)

CSDN如何获取C币

如何获得年份序列,因为我只获得月份序列

求教,如何获得comboBox中当前选择的值

怎样获得权限