Home >Web Front-end >JS Tutorial >Catching unhandled Promise errors
By listening to the unhandledrejection event, you can capture unhandled Promise errors.
In order to ensure readability, this article adopts free translation rather than literal translation, and the source code has been extensively modified. In addition, the copyright of this article belongs to the original author, and the translation is for learning only.
When writing asynchronous code using Promise, use reject to handle errors. Sometimes, developers usually ignore this, resulting in some errors not being handled. For example:
function main() { asyncFunc() .then(···) .then(() => console.log('Done!')); } |
Because the catch method is not used to capture the error, when asyncFunc()Functionreject, the error thrown is not handled.
This blog will introduce how to catch unhandled Promise errors in browsers and Node.js respectively.
Some browsers (such as Chrome) are able to catch unhandled Promise errors.
Listen to the unhandledrejection event to capture the unhandled Promise error:
window.addEventListener( 'unhandledrejection', event => ···); |
This event is an instance of PromiseRejectionEvent, which has the 2 most important properties:
promise
: reject Promise
reason
: reject value of Promise
Sample code:
window.addEventListener('unhandledrejection', event => { console.log(event.reason); // 打印"Hello, Fundebug!" }); function foo() { Promise.reject('Hello, Fundebug!'); } foo(); |
unhandledrejection event, so it can automatically capture unhandled Promise errors.
rejectionhandledWhen a Promise error is not handled initially, but is later handled, therejectionhandled event will be triggered:
PromiseRejectionEvent.
Sample code:
The above is the detailed content of Catching unhandled Promise errors. For more information, please follow other related articles on the PHP Chinese website!