Error handling of API responses is not a part of this module since the main goal is to provide an authentication layer and configured API client, but on this page, you can find useful hints.
When Laravel returns an error of any kind (403, 404, 500, etc), the module will throw this as an exception that has a generic Error type.
By default, when Laravel API returns a 401 status code, the module will reset the user identity and redirect to sanctum.redirect.onAuthOnly route (if sanctum.redirectIfUnauthenticated is enabled).
Error type check
This is how you can check what type of error you received
components/LoginForm.vue
import { FetchError } from 'ofetch';
const { login } = useSanctumAuth();
const userCredentials = {
email: 'user@mail.com',
password: '123123',
};
async function onCredentialsFormSubmit() {
try {
await login(userCredentials);
} catch (e) {
if (error instanceof FetchError && error.response?.status === 422) {
// here you can extract errors from a response
// and put it in your form for example
console.log(e.response?._data.errors)
}
}
}
Sometimes, it is not convenient, especially when it comes to validation errors in plenty of forms and components.
Error helper
Here you can get inspiration from error handling specifically for this case and implement it your way.
Create a new composable useApiError with the following content: