Using visual studio I created a snippet which helps me surround my already written or new code into a try-catch-finally block. I use axios for REST so there had to be separate error handling method so that users can cleanly view the error result and report it to the support team.
Code:
try {
//Start the loading bar so user can know something is running in background
this.$store.commit("isLoading", true);
//Some axios code runs here...
const response = await this.axios.post(process.env.VUE_APP_API_ExampleAPI, { param1: 'blaa', param2: 'blaa2' });
//Once done result is going to be shown in a modal using vuex as store
//200 response requests will always return the response in the format of an object and message containing in "message" parameter
this.$store.commit("successMessage", response.data.message);
//Now user is shown the modal
this.$store.commit("successModal", true);
}
catch (error) {
//In case the error is via axios request
if (error.isAxiosError) {
var concatMessages = '';
Object.entries(error.response.data.errors).forEach(([key, value]) => concatMessages += value);
this.$store.commit("errorMessage", concatMessages);
this.$store.commit("errorModal", true);
}
//Other non-axios errors i.e. syntax error, code error etc...
else {
this.$store.commit("errorMessage", error.toString());
this.$store.commit("errorModal", true);
}
}
//Finally block stops the progress bar loading indicating background process isn't anymore
finally {
this.$store.commit("isLoading", false);
}
Now I feel like there is too much code in it despite it helps in development. I mean it is repeated in almost every function/method.
There has to be a way to reduce this code or improve it to avoid repetition in most of the functions but I am not sure what it could be.