1

this.$auth.loginWith returns a promise, but I am unsure if I should wrap it in a try/catch or just use a catch on the promise.

Which is the correct way?

Try/Catch:

async login() {
            try {
                const response = await this.$auth.loginWith('laravelSanctum', {
                    data: {
                        email: 'xxx',
                        password: 'xxx',
                    },
                });

                this.$auth.setUser(response.data.data);
            } catch (e) {

            }
        },

Catch:

async login() {
                const response = await this.$auth.loginWith('laravelSanctum', {
                    data: {
                        email: 'xxx',
                        password: 'xxx',
                    },
                }).catch(function(e) {
                });

                this.$auth.setUser(response.data.data);
        },
panthro
  • 22,779
  • 66
  • 183
  • 324
  • What have you done so far to find an answer on your own? -> [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) – Andreas Jan 13 '22 at 12:00
  • 3
    These do two different things. They don't have to but the way you've written them, the first piece of code will *not* call `this.$auth.setUser();` on a failure. The second piece of code will assign `undefined` to `response` (since the `.catch()` doesn't return anything), and `this.$auth.setUser(response.data.data);` *will* be called. Then fail because `response` is `undefined`, thus `response.data` will throw an error. – VLAZ Jan 13 '22 at 12:00
  • Don't do either of these. Ignoring errors is not a good practice, if you really have a reason at least add a comment why this is intended. – Bergi Jan 14 '22 at 05:51

1 Answers1

2

In general, it's best practice not to combine async/await with using the promise methods (.then, .catch), so your try/catch would usually be the better of those two options.

And @VLAZ put his finger on one of the good reasons for that: When you mix metaphors like that, it can be tricky to read the flow, and in your case the version using .catch will actually cause an error because the your specific catch handler converts rejection to fulfullment with undefined, so the code continues after the await, and tries to do this.$auth.setUser(response.data.data); when response is undefined, causing a new error that seems unrelated to login.


But normally, even better is to not handle the rejection at all so that the caller knows whether the login worked or not (because login will reject if there was an error). But for entry points into your code (event handlers, that kind of thing), inline handling of rejections can have a place. It depends on how login is used. Other than entry points, default to letting the error/rejection propagate to the caller.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875