Home > Back-end >  Error in promise catch does not trigger global error handler
Error in promise catch does not trigger global error handler

Time:07-16

Why does an error thrown in a promise reject/catch method not trigger the global error handler? How can a global error handler that includes these be created? In my app the global error handler logs the error.

function doPromise() {
    return Promise.reject()
}

window.addEventListener('error', function (e) { console.log('Global handler '   e.message) })

doPromise()
 .then()
 .catch(e => {
    console.log('Promise catch')
    throw new Error('Promise catch error')  // Does not trigger global error handler
  })
    
throw new Error('Core error')  // To prove global error handler is working

CodePudding user response:

This is not an error, but Unhandled Rejection:

The unhandledrejection event is sent to the global scope of a script when a JavaScript Promise that has no rejection handler is rejected

Working version of the code:

function doPromise() {
    return Promise.reject()
}

window.addEventListener('error', function(e) {
    console.log('Global handler '   e.message)
})
window.addEventListener('unhandledrejection', event=>{
    console.log('Unhandled rejection', event)
}
);

doPromise().then().catch(e=>{
    console.log('Promise catch')
    throw new Error('Promise catch error')
    // Does not trigger global error handler
}
)

throw new Error('Core error')
// To prove global error handler is working
  • Related