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);
},
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.