DEV Community

Discussion on: Better error handling with async/await

Collapse
 
calvintwr profile image
calvintwr

You are much much better off just using #catch at the top level caller.


const fetchUsers = async () => {
    return await fetch('')
}

const fetchPosts = async () => {
    throw Error('error in getting posts')
    return await fetch('')
}

const fetchEverything() = async() => {
    return [
        fetchUsers(),
        fetchPosts()
    ]
}

// fetchEverything, as the top level caller, should have the catch handler
fetchEverything().then(results => {
    // do something with results
}).catch(err => {
    // do something with err. You have two non-mutually-exclusive options.

    // console.log and don't crash anything
    console.log(err)
    alert('Something has failed. Please try again later.')

    // AND/OR, you can throw the error to "bubble up" the error.
    // If there is another caller with a catch handler, this error will bubble up there.
    // Otherwise, it will get thrown into the main scope to stop execution.
    throw err
})
Enter fullscreen mode Exit fullscreen mode