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.
JavaScript
x
15
15
1
function doPromise() {
2
return Promise.reject()
3
}
4
5
window.addEventListener('error', function (e) { console.log('Global handler ' + e.message) })
6
7
doPromise()
8
.then()
9
.catch(e => {
10
console.log('Promise catch')
11
throw new Error('Promise catch error') // Does not trigger global error handler
12
})
13
14
throw new Error('Core error') // To prove global error handler is working
15
Advertisement
Answer
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:
JavaScript
1
22
22
1
function doPromise() {
2
return Promise.reject()
3
}
4
5
window.addEventListener('error', function(e) {
6
console.log('Global handler ' + e.message)
7
})
8
window.addEventListener('unhandledrejection', event=>{
9
console.log('Unhandled rejection', event)
10
}
11
);
12
13
doPromise().then().catch(e=>{
14
console.log('Promise catch')
15
throw new Error('Promise catch error')
16
// Does not trigger global error handler
17
}
18
)
19
20
throw new Error('Core error')
21
// To prove global error handler is working
22