I am currently working on implementing a global error handling system in my Vue application. Within my project, I have an api.service.js file that contains the necessary code for Axios setup and various HTTP request functions such as get and post:
/**
* Service to handle HTTP requests using Axios
*/
const ApiService = {
init(apiBaseUrl) {
Vue.use(VueAxios, axios);
Vue.axios.defaults.baseURL = apiBaseUrl;
},
/**
* Set default headers for HTTP requests
*/
setHeader() {
Vue.axios.defaults.headers.common[
"Authorization"
] = `Bearer ${JwtService.getToken()}`;
},
setHeaderwToken(token) {
Vue.axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
},
/**
* Perform a GET HTTP request
* @param resource
* @param slug
* @returns {*}
*/
get(resource, slug = "") {
// Code for handling different scenarios and errors
});
export default ApiService;
Within my Vue component, I make use of my ApiService like so:
ApiService.get("MyFunction")
.then((response) => {
console.log("MyFunction " + response);
.catch((error) => {
console.log("MyFunction " + error);
});
},
https://i.stack.imgur.com/gJHd1.png
I attempted to implement a custom response (myResponse) and return it, but it kept returning as undefined. This led me to believe that my approach was incorrect. My goal is to be able to catch any error codes returned from the API when a function is called, such as 500, 401, or 404. Specifically, if a 401 error is encountered, I want to call the "CheckToken" function. If the CheckToken function returns "OK," I aim to return "noAuthorityValid" indicating valid token but unauthorized access. If the CheckToken does not return OK, then I want to return noTokenValid. Furthermore, I want to handle this logic within my Vue component where I call my function:
ApiService.get("MyFunction")
.then((response) => {
console.log("MyFunction " + response);
//if (response.statusText == noAuthorityValid)
{
//show snackbar("you are not authorized for this function")
}
})
.catch((error) => {
console.log("MyFunction " + error);
});
},