简体   繁体   中英

NodeJS Package: error handling

I have some code that uses an Overwatch API to grab some data. This is what I currently have:

OWoverallStats: (playerName, mode, region) => {
    mode = (typeof mode === 'undefined') ? 'competitive' : mode.toLowerCase();
    region = (typeof region === 'undefined') ? 'us' : region.toLowerCase();

    playerName = playerName.replace('#', '-');

    return fetch(`https://owapi.net/api/v3/u/${playerName}/stats`)
        .then(res => res.json())
        .then(data => {
            return data[region].stats[mode].overall_stats;
        });
}

This works fine, providing you enter a playerName that actually exists. The code I used to test this is:

core.OWoverallStats('Calvin-1337', 'quickplay', 'eu').then(data => {
    console.log(data.tier) // grandmaster
}).catch(e => {
    console.log(e);
});

In the actual code, I can check if the error code is 404 (player doesn't exist) but then I don't know what I can do with that. I don't want to throw an error, or console log it as if someone implemented this say into a Discord Bot, I'd want the person using the code to say what they wanted to do with the error.

When fetch has a response, if the status is 404 Simply throw an Error. The caller of your code can then catch it and handle however he likes.

For example, your code:

return fetch(`https://owapi.net/api/v3/u/${playerName}/stats`)
.then((res, meta) => {if (meta.status ===404) throw new Error('NoPlayer')})

The caller of your code:

core.OWoverallStats('Calvin-1337', 'quickplay', 'eu').then(data => {
}).catch(e => {
//this is where he can handle the error flexibly
});

You may see other error handling practices here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM