Home > other >  When should I use try catch instead of then catch?
When should I use try catch instead of then catch?

Time:09-28

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(...)?

CodePudding user response:

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.

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.

CodePudding user response:

When you use promises(asynchronous operations) then you need to handle the exception in case of an error. So In this case you can use .then().catch(err) {}

When you have synchronous code, use try/catch for exception handling.

  • Related