Is there a way to add a catch all block to run after an entire promise chain? In the example below, get
is a generic lib method that handles some data processing and returns the data to callGet
which takes the data and handles the UI in whatever way. I want to make a catch all error handling block that runs after the entire chain runs. I want the catch all finally
block to live on the get
block because it is the generic lib method.
// generic lib method used throughout codebase
function get(url, data) {
return axios.get(url, data).then(res => {
// handle response in whatever way (1)
}).catch(error => {
// handle error in whatever way (2)
}).finally(() => {
// RUN BLOCK AFTER callGet CHAIN (3)
});
}
// specific call from somewhere within the codebase
function callGet() {
get('/test', {}).then(res => {
// do more with response from get (4)
}).catch(err => {
// handle error in UI somehow (5)
});
}
callGet();
If this were a single chain written out, the order would run like this: (I know this isn't how promises work - just pseudocode to write out the thoughts)
axios.get(url, data).then(res => {
// (1) then in get block
}).then(res => {
// (4) then in callGet block
}).catch(err => {
// (2) catch in get block if errors in get block
}).catch(err => {
// (5) catch in callGet block if errors in callGet block
}).finally(() => {
// (3) run after callGet block
})
Update:
Ultimately ended up going with bluebird's onPossiblyUnhandledRejection http://bluebirdjs.com/docs/api/promise.onpossiblyunhandledrejection.html
It ends up doing what I need it to to catch any unhandled rejections that the dev isn't specifically handling.