Tips for creating a custom axios response depending on the error code returned by the response

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);
    });
},

Answer โ„–1

I couldn't figure it out using api.service.js, so I came up with a workaround. I decided to import axios in each component where I needed to make an axios call;

import axios from "axios";

Then, I utilized axios like this:

 axios({
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
          Accept: "application/json",
        },
        url: "MyFunction",
        method: "get",
      })
      .then((response) => {....}

Furthermore, within the created function of my top component (top parent), I employed axios.interceptors.response as follows:

axios.interceptors.response.use(
      (response) => {
        return response;
      },
      (error) => {
        this.handleError(error);
        return Promise.reject(error);
      }
    );

Here is my handleError function:

handleError(error) {
  if (error.response.status == 401) {
    if (error.response.data.includes("expiredToken")) {
      this.showSnackbar("Token has expired");
      setTimeout(() => {
        if (!window.location.href.includes("login")) {
          this.$router.push({ name: "login" }).then(() => {
            this.$store.dispatch(LOGOUT); //Clears user data,
          });
        }
      }, 2000);
    } else if (
      error.response.data.includes(
        "UnauthorizedFunction"
      )
    ) {
      this.showSnackbar("You are not authorized for this function.");
    } else {
      this.showSnackbar("An error occurred.");
    }
  } else {
  this.showSnackbar("An error occurred.");
  }
}

This frustrating issue consumed 2.5 days of my time...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to perform a redirect in Node.js and Express.js following a user's successful login

As I work on developing an online community application with nodejs/expressjs, one persistent issue is arising when it comes to redirecting users to the correct page after they have successfully signed in. Despite reading several related articles and attem ...

Show information upon opening

I am currently working on a project that involves 4 different divs, and I need the content of each div to be displayed based on dropdown selection. I found a code snippet that was close to what I needed, but after trying to adjust it, I haven't been a ...

What could be the reason for the lack of reactivity in computed properties within my Vue 3 application

Problem โœ… Vue 2: computed properties get updated after a Vuex store mutation. โŒ Vue 3: computed properties do not update after a Vuex store mutation. Vuex 4 Objective: Retrieve posts from Firestore, add them to "postsArray", and commit the mutation. ...

Error occurred while attempting to access querystring values

Is there a reason why 2 out of the 3 querystring parameters have values, while one is undefined? <li class="@ViewBag.ShowNext">@Html.RouteLink("Next ยป", "Search", new { page = @ViewBag.NextPage, q = @ViewBag.TextClean, Option = @ViewBag.Option }, n ...

Determine the specific button that was clicked within a React component

I have a challenge with dynamically generated material UI buttons. I am trying to identify which button was clicked by obtaining the value of the name attribute that I assigned to each button. Is there a way to accomplish this? In essence, I need to retrie ...

Angular 14 is experiencing issues with NgRx Store failing to properly recognize the payload

The issue lies in TypeScript not recognizing action.payload.index as a valid property. I am unsure how to resolve this problem and make the 'index' visible in my project. shopping-list.actions.ts import {Action} from "@ngrx/store"; im ...

Tips on creating a keypress function for a div element with the contenteditable attribute

Hey there, I have managed to create a textarea within a div by using -webkit-appearance. However, I am currently struggling to add an event to this div on key press. I have been trying my best to figure it out but seem to be missing something. If you coul ...

Exploring the process of iterating through JSON data using JSON.parse

After making a request to my Django server for data, I utilized JSON.parse to convert the data into a JSON object. My goal is to iterate through each attribute of the object's field and execute the function createDiv on each one. function load_blog( ...

Tips for implementing HTTP requests in Angular 2 without TypeScript

The demonstrations provided by the angular team only illustrate injecting Http for typescript. https://angular.io/docs/js/latest/api/http/Http-class.html How can this be accomplished in JavaScript? import {Http, HTTP_PROVIDERS} from 'angular2/http& ...

Utilizing directives while initiating dynamic components

I've been exploring the capabilities of dynamically creating components using the ComponentFactoryResolver. const factory = this.componentFactoryResolver.resolveComponentFactory(FooComponent); const component = this.templateRoot. ...

Dynamic way to fetch computed properties in VueJS

I am trying to find a way to calculate the sum of computed properties that begin with the string calculateSum. The challenge is that I cannot access their names using this.computed. Here is my approach: getSubTotal(){ var computed_names = []; var ...

What is the process for incorporating multiple HTML pages into an Ionic hybrid mobile application?

Struggling to combine my sign in and sign up pages into a single index.html page. I'm currently working on a project involving Hybrid mobile app development. ...

Can you show me a way to use jQuery to delete several href links using their IDs at once?

Currently facing a challenge with removing multiple href links that share the same ID. Here is a snippet of my code: $('.delblk').click(function(e) { e.preventDefault(); var id = $(this).attr('id').substr(7); ...

Troubleshooting Vue 2 TypeScript Components Import Issue in VS Code

Has anyone experienced issues with TS pointing errors when importing custom components into a .vue file using the options api and webpack? The import is successful, everything works after bundling, but I'm still encountering annoying errors in the .vu ...

What is the best way to filter out duplicate objects in JavaScript?

I have the following code snippet: let self = this; self.rows = []; self.data.payload.forEach(function (item, index) { if (!(self.rows.includes(item))) { self.rows.push(item); } }); The issue is that includes always returns false. Each ite ...

Scroll Reveal in Vue.js: Implementing a Dynamic Footer

Trying to implement a footer with scroll reveal functionality similar to this example: https://codepen.io/nickcil/pen/Eoqiv #footer { height: 200px; position: fixed; left: 0; bottom: 0; z-index: -1; } While the implementation is straightforward ...

Executing a JavaScript function to trigger a PHP script that saves data into a MySQL database

I have a button in my HTML file that, when clicked, should insert data into a database and then reload the page. I am calling a JavaScript function within the onclick event to handle this. Below is the JavaScript function: function grandFinale() { i ...

Ways to navigate the user to various screens

I'm currently developing an app that navigates users to various sections using Vue 3 and the Vue router. However, I'm facing a challenge in displaying different pages. When trying to show a new page, it doesn't display as expected. It seems ...

Upon selecting multiple checkboxes, corresponding form fields will be displayed based on shared attributes

When multiple checkboxes are selected by the user, corresponding form fields should appear based on the checkboxes. For example, if both flight and hotel checkboxes are checked, then the full name and last name fields should be displayed while other fields ...

Trigger a Nuxt/Vuejs event upon completion of rendering all page components

Is there a way to trigger an event after all components on a page have finished rendering? I've attempted using the page mounted event, but it only fires the first time. I need an event to be triggered each time the route changes on the client side an ...