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

The concept of dynamic schema in Mongoose allows for flexibility and

Currently, I am working on creating a product schema that involves setting pricing in different currencies. However, I am facing confusion regarding how to dynamically create currency options. The pricing may vary in one currency or multiple currencies as ...

How to utilize the Ember generate command for an addon

In my Ember addon project, the package.json file looks like this: { "name": "my-addon-ui", "version": "1.0.0", "devDependencies": { "test-addon": "http://example.com/test-addon-1.1.1.tgz", } } Additionally, the package.json file of the depe ...

Issues with React's onSelect event functionality are persisting

Is there an event handler in React for the onSelect statement? For example, when a user highlights some text within a paragraph using their mouse, is there a way to trigger an event that extracts the highlighted text? import React, { Component } from &apo ...

Easily toggle between different content within the same space using Twitter Bootstrap Tabs feature. Display the tabs

I made a modification to the bootstrab.js file by changing 'click' to 'hover': $(function () { $('body').on('hover.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) { e.p ...

"I'm trying to incorporate react-datepicker into my ReScript application, but I'm struggling to

I am attempting to incorporate an external library like react-datepicker into my project. Below is the code snippet and how I am using it: module DatePicker = { @react.component @module("react-datepicker") external make: () => React.eleme ...

Using jQuery UI to create sortable lists that are connected and have hidden overflow features

How can I hide overflow from two fixed-height divs containing sortable lists connected to each other without affecting their connection? For example, if overflow is set to hidden, the list item doesn't display when dragged outside of the div. I' ...

What is the reason behind the undefined value of "this" in this particular class method?

I have scoured the depths of the internet in search of a solution, but I am still grappling with an issue related to a JS class I am developing for a Micro Service (still learning as I go). When attempting to call a method within a class on an instantiate ...

What could be causing my bootstrap-switch to malfunction?

Here is the snippet of code I am working with: jQuery.each($('.onoffswitch-checkbox'), function(i, slotData) { console.log($(slotData).bootstrapSwitch('state')) }) <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1 ...

Tips for incorporating dynamic parameters/variables into templates displayed using ng-bind-html or a custom directive (within ng-repeat)

EDIT: I have created a solution sample based on the initial answer. However, I am open to further suggestions and would appreciate any help in filling the gaps in my knowledge (please refer to the comments). plnkr.co/edit/mqGCaBHptlbafR0Ue17j?p=preview OR ...

When attempting to display a sub view in Express, a 404 error is encountered

I am currently working with express and jade to display a web page. My intention is to render the page using this format 'http://127.0.0.1:5000/services/landfreight' but I keep encountering a 404 error. router.get('/service/landfreight' ...

The ajax response is being deserialized prior to being parsed by the

In my API controller, I need to respond with a model that includes a decimal property. However, the response type is simply a string. I am aware that converting large decimal data to a JavaScript number may result in some data loss. Therefore, I am consi ...

Troubleshooting CSS Hover Not Displaying Properly in Angular 14

In the footer class of my HTML, there is a code snippet with chevrons: <div class="link-list"> <div *ngFor="let link of insideLinksLeft | originalOrderKeyValue" class="link"> <a [href]="link.val ...

Learn the best way to handle special characters like <, >, ", ', and & in Javascript, and successfully transfer escaped data from one text box to another

I am seeking a way to use JavaScript to escape special characters. I came across a code snippet on this URL: http://jsperf.com/encode-html-entities. It successfully handles <>&, but I have encountered an issue with double quotes ("). The JavaScri ...

Search through a JSON array to find a specific element and retrieve the entire array linked to that element

Recently, I've been working with a json array that dynamically increases based on user input. Here's a snippet of the json code I'm dealing with: [{"scheduleid":"randomid","datestart":"2020-06-30",&quo ...

What could be the reason for the child element not occupying the full height of its parent container?

* { padding: 0; margin: 0; box-sizing: border-box; } body { margin: 50px; } .navbar { display: flex; align-items: center; justify-content: center; color: darkgreen; font-family: 'Vollkorn', serif; font-size: 1.2rem; font-w ...

Using esri-loader in Nativescript applications

I'm currently facing an issue while trying to incorporate esri-loader into my Nativescript Vue application in order to display a basic map. The code snippet I am using is outlined below: <script> import * as esriLoader from 'esri-loader&ap ...

What steps should I take in modifying my existing code to use jQuery to set my div to a minimum height rather than a fixed height?

Could someone assist me in adjusting my div to have a min-height instead of a regular height? Whenever I click on the "Learn more" button, it extends past my div because the function is designed to set a specific height rather than an equal height. $.fn.e ...

The application is functional, however, the initial controller within is experiencing difficulties

Setting up a controller in my application based on a tutorial. The first two divs are displaying correctly but the ContraAss controller is not rendering and only shows {{info}}. What am I missing here? (NB. Probably something simple, but with limited exper ...

Storing various duplicates of items in local storage

Looking for help with storage settings in HTML/JavaScript as I work on a mobile not taking app using Phonegap. My goal is to allow users to input a note name and content, save them into a jquery mobile list, and see them on the home screen. However, I&apos ...

Absence of event firing in .on method in Asp.NET Core 6 when using JQuery

I am currently working on an ASP.NET Core 6 application that utilizes JQuery. Here is the JQuery code snippet I have implemented in my page: @section Scripts { @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); } ...