Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use try catch instead of then catch?

The question is simple, but I haven't found the answer anywhere.

When should i use try catch? in the code below I use try catch to handle the return of a request:

async findUsers() {
    this.loading = true;

    try {
        const [users, count] = await this.api.get('/users/list');

        this.users = users;
        this.totalPages = Math.ceil(parseInt(count) / 10);
    }
    catch (error) {
        this.Messages.requestFailed(error);
    }
    finally {
        this.loading = false;
    }
}

Would it be a good practice to use then(...).catch(...)?

like image 226
Tchiteu Abloh Avatar asked Sep 09 '25 19:09

Tchiteu Abloh


1 Answers

The difference is in how you're handing Promises.

If you're using await to handle the Promise then you wrap it in a try/catch. Think of await as a way to make asynchronous operations semantically similar to synchronous operations (at least within the context of the function in which it's being awaited, consuming code notwithstanding).

But if you're not using await and are instead handling the Promise by appending .then() to it then you'd append a .catch() to that chain to catch failures from within the asynchronous operation.

Because a try/catch isn't going to catch an exception that happens from within the asynchronous operation if that operation isn't awaited.

like image 108
David Avatar answered Sep 12 '25 08:09

David