譯者按: 通過監聽unhandledrejection事件,可以捕獲未處理的Promise錯誤。
為了保證可讀性,本文采用意譯而非直譯,並且對源代碼進行了大量修改。另外,本文版權歸原作者所有,翻譯僅用於學習。
使用Promise編寫異步代碼時,使用reject來處理錯誤。有時,開發者通常會忽略這一點,導致一些錯誤沒有得到處理。例如:
function main() { asyncFunc() .then(···) .then(() => console.log('Done!')); }
這篇博客將分別介紹在瀏覽器與Node.js中,如何捕獲那些未處理的Promise錯誤。由於沒有使用catch方法捕獲錯誤,當asyncFunc()函數reject時,拋出的錯誤則沒有被處理。
瀏覽器中未處理的Promise錯誤
一些瀏覽器(例如Chrome)能夠捕獲未處理的Promise錯誤。
unhandledrejection
監聽unhandledrejection事件,即可捕獲到未處理的Promise錯誤:
window.addEventListener('unhandledrejection', event => ···);
promise
: reject的Promise這個事件是PromiseRejectionEvent實例,它有2個最重要的屬性:
reason
: Promise的reject值
示例代碼:
window.addEventListener('unhandledrejection', event => { console.log(event.reason); // 打印"Hello, Fundebug!" }); function foo() { Promise.reject('Hello, Fundebug!'); } foo();
rejectionhandledFundebug的JavaScript錯誤監控插件監聽了unhandledrejection事件,因此可以自動捕獲未處理Promise錯誤。
當一個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事件也沒問題。
Fundebug的Node.js錯誤監控插件監聽了unhandledRejection事件,因此可以自動捕獲未處理Promise錯誤。
參考
關於Fundebug
Fundebug專注於JavaScript、微信小程序、微信小游戲、支付寶小程序、React Native、Node.js和Java線上應用實時BUG監控。 自從2016年雙十一正式上線,Fundebug累計處理了10億+錯誤事件,付費客戶有Google、360、金山軟件、百姓網等眾多品牌企業。歡迎大家免費試用!