Error Handling
While the nuxt-sanctum-authentication
module focuses on providing a secure authentication layer and a configured API client, it does not include built-in error handling for API responses. However, here are some useful tips for managing errors effectively.
When your Laravel backend returns an error (such as 403, 404, 500, etc.), the module will throw it as an exception, typically of the generic Error
type.
Checking Error Types
To determine the specific type of error you've encountered, you can use the following approach:
components/LoginForm.vue
javascript
import { FetchError } from 'ofetch';
const { login } = useSanctum();
const userCredentials = {
email: 'user@mail.com',
password: '123123',
};
async function onCredentialsFormSubmit() {
try {
await login(userCredentials);
} catch (e) {
if (e instanceof FetchError && e.response?.status === 422) {
// You can extract validation errors from the response
// and display them in your form
console.log(e.response?._data.errors);
}
}
}
This method is useful, but it can become cumbersome, especially when dealing with validation errors across multiple forms and components.