Kevin Powell - CommunityKP-C
Kevin Powell - Community14mo ago
6 replies
Faker

Why did we use a .catch() rather than a catch() block while handling errors

Hello guys, can someone explain why in the following code, we use a .catch outside the function body that is when the function run is being called. Why don't we use a catch block directly after the try ? If we don't use a catch block inside, then what's the need of the try, we can remove it ?

From what I have understand, this is why we might want to use a .catch() outside the function body rather than inside:

we don't want the flow inside the function to stop every time there is an error with our return promises, instead of handling each error 1 at a time, let's just handle it at an upper level, that is when we call the function

async function run(username,password) {
    try {
        const database = client.db('socialMedia');
        const users = database.collection('users');
        const doc = {user : `${username}`, pwd : `${password}`};

        const result = await users.insertOne(doc);
        console.log(result);
    }
    finally {
        await client.close();
    }
}

run('username','secret')
    .catch(console.dir);
Was this page helpful?