Moshe
Moshe

Reputation: 5159

Unhandled promise rejection even though I do handle it

I wrapped a request-promise-native call in a function that returns a promise.

import request from 'request-promise-native';
function requestWrapper(url) {
    return request(url)
        .then(data => {...})
        .catch(err => Promise.reject(err));
}

Simple right?

Now I'm using this function, and thenworks ok, but catch never catches the Promise.reject:

requestWrapper('http://some-url.com')
    .then(data => {...})
    .catch(err => console.log(err));

I never get to the call's catch! If I change the return statement in the catch of requestWrapper to this:

.catch(err => err)

or even this:

.catch(err => Promise.resolve(err))

to return a resolve, I get the error stack on the then of the requestWrapper call just as expected.

And node shouts:

(node:24260) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): ...

Upvotes: 6

Views: 7588

Answers (2)

Moshe
Moshe

Reputation: 5159

Ok thanks to @pathurs and @Hendry I got what I needed.

First of all, the right way is what @Hendry suggested which was to not handle the catch in the wrapper, rather in the function call. This is the way I went:

function requestWrapper(url) {
    return request(url)
        .then(data => {...})
}
requestWrapper('http://some-url.com')
    .then(data => {...})
    .catch(err => console.log(err));

Great! But apparently, @pathurs way also works:

function requestWrapper(url) {
        return request(url)
            .then(data => {...})
            .catch(err => Promise.reject(err));
    }
    requestWrapper('http://some-url.com')
        .then(data => {...}, err => console.log(err));

I don't understand if that's a native feature, or some addition to request library: https://github.com/request/request-promise#thenonfulfilled-onrejected

Upvotes: 6

zabusa
zabusa

Reputation: 2719

if you are not getting that then do this workaround.

In order to handle rejections the following new events will be fired on process:

Event 'unhandledRejection':

Emitted whenever a possibly unhandled rejection is detected. This event is emitted with the following arguments:

reason the rejection reason of the promise susprected in having an unhandled rejection p the promise suspected in having an unhandled rejection itself.

process.on('unhandledRejection', function(reason, p){
    console.log("Possibly Unhandled Rejection at: Promise ", p, " reason: ", reason);
    // application specific logging here
});

For more info Unhandled Rejection

Upvotes: 4

Related Questions