0👍
First of all, I’d advise using axios’ Response Interceptor which is essentially a callback that gets executed every time a request has been completed so you don’t have to do error handling on each and every request.
Create a new file (for example axiosInstance.js
)
const axiosInstance = axios.create({
baseURL: 'https://example.com/api',
});
axiosInstance.interceptors.response.use((response) => {
return response;
}, (error) => {
switch(error.response.status) {
case 422:
// Here you will be able to process Laravel Validation Errors.
// You can for example display an error message using your favorite library
console.log("Error Message: " + error.response.data.message);
console.log("Error Object: " + error.response.data.errors);
break;
}
return Promise.reject(error);
}
export default axiosInstance;
As you can see you can access your response by using error.response
. This works for catch
blocks in simple axios requests aswell.
axios.get('https://example.com/xyz').catch(e => {
console.log(e.response);
});
The above interceptor in my first code block will do special handling for all Laravel Validation Errors since those are returned using HTTP Status 422 (Unprocessable Entity) by default.
To use it, instead of doing axios.get()
you can do:
import axiosInstance from './axiosInstance.js';
axiosInstance.get('https://example.com/xyz');
The logic you defined in the catch block of the interceptor will then be executed every time a request that was initiated using axiosInstance
. You can also append .catch()
again to the request to handle additional logic if a specific requests fails.
To handle additional error types, extend the interceptors switch
conditional statement. For example, exceptions like "The database is not available" are returned with status code 500 by Laravel. Usually, a simple message is then available to display to the user by using error.response.data.message
.
tl;dr
This is what you could do achieve what you are trying to do using your code:
axios.post('/task', data)
.then((res) => {
console.log(this.name + ".save() - response from insert (then): " + res);
this.snackbarMessage = "Created new task";
this.showMessageSnackbar = true;
this.showTable = true; //start showing ToDo table again
this.form.reset();
this.getTasks();
})
.catch((error) => {
console.log(this.name + ".save() - response from insert (catch): " + error.response);
// Given that your erroneous response contains 'message' (like laravel validation errors do):
console.log(this.name + ".save() - error: " + error.response.data.message);
this.snackbarMessage = "Failed to create new task";
this.showMessageSnackbar = true;
this.showTable = true; //start showing ToDo table again
})
- [Vuejs]-Dynamically create html table from an Array
- [Vuejs]-Reflect changes of same Vue Component to different routes