捕獲未處理的Promise錯誤

譯者按: 經過監聽unhandledrejection事件,能夠捕獲未處理的Promise錯誤。javascript

爲了保證可讀性,本文采用意譯而非直譯,而且對源代碼進行了大量修改。另外,本文版權歸原做者全部,翻譯僅用於學習。html

使用Promise編寫異步代碼時,使用reject來處理錯誤。有時,開發者一般會忽略這一點,致使一些錯誤沒有獲得處理。例如:java

function main() {
    asyncFunc()
    .then(···)
    .then(() => console.log('Done!'));
}

因爲沒有使用catch方法捕獲錯誤,當asyncFunc()函數reject時,拋出的錯誤則沒有被處理。node

這篇博客將分別介紹在瀏覽器與Node.js中,如何捕獲那些未處理的Promise錯誤。git

瀏覽器中未處理的Promise錯誤

一些瀏覽器(例如Chrome)可以捕獲未處理的Promise錯誤。github

unhandledrejection

監聽unhandledrejection事件,便可捕獲到未處理的Promise錯誤:chrome

window.addEventListener('unhandledrejection', event => ···);

這個事件是PromiseRejectionEvent實例,它有2個最重要的屬性:小程序

  • promise: reject的Promise
  • reason: Promise的reject值

示例代碼:微信小程序

window.addEventListener('unhandledrejection', event =>
{
    console.log(event.reason); // 打印"Hello, Fundebug!"
});

function foo()
{
    Promise.reject('Hello, Fundebug!');
}

foo();

FundebugJavaScript錯誤監控插件監聽了unhandledrejection事件,所以能夠自動捕獲未處理Promise錯誤。api

rejectionhandled

當一個Promise錯誤最初未被處理,可是稍後又獲得了處理,則會觸發rejectionhandled事件:

window.addEventListener('rejectionhandled', event => ···);

這個事件是PromiseRejectionEvent實例。

示例代碼:

window.addEventListener('unhandledrejection', event =>
{
    console.log(event.reason); // 打印"Hello, Fundebug!"
});

window.addEventListener('rejectionhandled', event =>
{
    console.log('rejection handled'); // 1秒後打印"rejection handled"
});


function foo()
{
    return Promise.reject('Hello, Fundebug!');
}

var r = foo();

setTimeout(() =>
{
    r.catch(e =>{});
}, 1000);

Node.js中未處理的Promise錯誤

監聽unhandledRejection事件,便可捕獲到未處理的Promise錯誤:

process.on('unhandledRejection', (reason, promise) => ···);

示例代碼:

process.on('unhandledRejection', reason =>
{
    console.log(reason); // 打印"Hello, Fundebug!"
});

function foo()
{
    Promise.reject('Hello, Fundebug!');
}

foo();

注: Node.js v6.6.0+ 默認會報告未處理的Promise錯誤,所以不去監聽unhandledrejection事件也沒問題。

FundebugNode.js錯誤監控插件監聽了unhandledRejection事件,所以能夠自動捕獲未處理Promise錯誤。

參考

關於Fundebug

Fundebug專一於JavaScript、微信小程序、微信小遊戲、支付寶小程序、React Native、Node.js和Java線上應用實時BUG監控。 自從2016年雙十一正式上線,Fundebug累計處理了10億+錯誤事件,付費客戶有Google、360、金山軟件、百姓網等衆多品牌企業。歡迎你們免費試用

版權聲明

轉載時請註明做者Fundebug以及本文地址:
https://blog.fundebug.com/2017/10/09/unhandled-pomise-rejection/