-1

Using: https://www.npmjs.com/package/snekfetch I am trying to catch the following error: UnhandledPromiseRejectionWarning: Error: 404 Not Found

On the website it shows: {"error":"not-found"}

Code:

const promise = new Promise(function(resolve, reject) {
    snekfetch.get('https://www.website.com/api/public/users?name=' + user).then(body => {
        const json = JSON.parse(body.text);
        const name = json.name;
        console.log(json);
        json ? reject(Error('It broke')) : resolve(name);
    });
});

promise.then((result) => {
    console.log(result);
    console.log('works');
}).catch((error) => {
    console.log(error);
    console.log('does not work');
});

I tried to check if there is json: json ? reject(Error('It broke')) : resolve(name); and the resolve works but I can not seem to catch the 404 Not Found error, how can I do this?

Aqua
  • 3
  • 3

1 Answers1

0

The problem is that you're tripping over the new Promise antipattern, and not propagating errors correctly while doing so. :-)

The correct way to fix it is not to use new Promise at all:

const promise = snekfetch.get('https://www.website.com/api/public/users?name=' + user)
    .then(body => {
        const json = JSON.parse(body.text);
        const name = json.name;
        return name;
    });

Now, promise will resolve or reject based on the promise from snekfetch; if it resolves, it will resolve with the name from the JSON. (I'm assuming you do really need to parse the JSON, that snekfetch won't do it for you.)

If you had a good reason for wrapping another promise around it (there doesn't seem to be one here), you'd need to ensure that you propagated the error from snekfetch's promise to yours: .catch(reject):

// NOT APPROPRIATE HERE, but how you'd do it if you used an explicit new promise
const promise = new Promise((resolve, reject) => {
    snekfetch.get('https://www.website.com/api/public/users?name=' + user)
        .then(body => {
            const json = JSON.parse(body.text);
            const name = json.name;
            resolve(name);
        })
        .catch(reject);
});
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • "*If you had a good reason for wrapping another promise around it*" - there **never** is. It's not like you're re-implementing something like `Promise.all`. – Bergi Aug 30 '18 at 12:41
  • @Bergi - I allow for what I can't immediately imagine. :-) But mostly, I just wanted to explain why the error wasn't getting propagated. (But for the record: There's always the possibility of converting a *thenable* into an actual promise, though you'd do that with `Promise.resolve`. After all, JS itself does that all the time, spawning promises all over the place... :-) ) – T.J. Crowder Aug 30 '18 at 13:54