What is the correct way to handle errors in TypeScript when using Axios?

I've got this code snippet that's currently working:

                try {
                    self.loadingFrameMarkup = true;
                    const { data }: AxiosResponse<IMarkupFrameData> = yield axios.post<IMarkupFrameData>(
                        Endpoints.LoadMarkupFrame,
                        {
                            studyID: self.studyID,
                            frameIndex: frameIndex,
                        }
                    );

                    result = {
                        ...data,
                        layers: data.layers.filter((it) => it),
                    };
                    self.loadingFrameMarkup = false;
                } catch (error: AxiosError | Error) {
                    if (error?.response?.status === 401) {
                        self.state = QueueState.Unauthorized;
                    } else {
                        self.state = QueueState.Failure;
                    }
                }

typescript-eslint is flagging an error: Catch clause variable type annotation must be 'any' or 'unknown' if specified.ts(1196) (alias) interface AxiosError<T = unknown, D = any>

What should be the error type in Axios?

Answer №1

When handling errors in the catch block, it is not possible to directly specify the type definition of the error. For more information on this topic, you can refer to this source. The recommended approach is to define the type within the catch block, like so:

catch (err) {
       if ((error as AxiosError)?.response?.status === 401) {
             self.state = QueueState.Unauthorized;
           } else {
              self.state = QueueState.Failure;
         }
     }

Answer №2

One approach you could take is to

    attempt {
        ...
        ...
        ...
    } catch (error) {
      print(error as AxiosError)
      // or
      // const error = error as AxiosError
    }

Answer №3

In TypeScript, the types are only present during the compilation process. Once the code is compiled, it all boils down to plain JavaScript with no types.

Implementing type filters on catch clauses would necessitate checking the types of errors at runtime, but there isn't a foolproof method for doing so. As a workaround, it's best to simply assign the error to any or unknown and then perform a cast if needed.

catch (error: Error | any){
/// code
}

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 approach for declaring helper functions and constants within nest.js?

Currently, I am delving into the world of nest.js and building an API using it. However, I have hit a roadblock when it comes to defining constants and helper functions. Like many APIs, some of my endpoints require pagination, and I want to set a default ...

Nextjs google places autocomplete not providing accurate suggestions

I'm attempting to utilize Google autocomplete to retrieve the names of mosques specifically in the United Kingdom. However, the data I am receiving is global and not limited to mosques. Here is my code: import axios from "axios"; export def ...

Tips for dynamically modifying style mode in Vue.js

I am looking to implement a feature where the style can be changed upon clicking a button. In my scenario, I am using Sass/SCSS for styling. For example, I have three different styles: default.scss, dark.scss, and system.scss. The code for dark.scss look ...

How to choose a particular Excel spreadsheet in Angular before importing the file?

I am currently working on a new feature that allows users to choose a specific Excel worksheet from a dropdown list before importing a file. However, I am facing some difficulty in adding the worksheet names to the dropdown list. Right now, I have placehol ...

Can you explain the distinction between an optional field and a union?

Is there a significant distinction between the following structures: { ok: boolean; } | { ok: boolean; error: any; } and: { ok: boolean; error?: any; } I have observed variance in the inferred types of frontend methods' return ou ...

Retrieving the slug from the parameters in the API response using this.$route

I am currently using vue-router to navigate from an 'index' page displaying records for a particular resource. I have set up a router-link to direct you to a separate page for each individual record. Although the route is functioning correctly, I ...

The issue encountered is a TypeError stating that it is unable to retrieve properties of an undefined value, specifically in relation to the 'imageUrl

When I include the following line of HTML code: <td> <img align="center" [src]="productByBarCode.imageUrl" /> </td> An error is thrown by the console: ERROR TypeError: Cannot read properties of undefined (reading &a ...

Trouble with Nextjs link not functioning properly with a URL object when incorporating element id into the pathname

Recently I added translations to my website, which means I now need to use a URL object when creating links. Everything has been going smoothly with this change except for one issue: when I try to click a link that points to /#contact. When simply using h ...

angular 6 personalized material icons with ligature assistance

Can I create my own custom material icons with ligature support? Currently, I use svgIcon to get Custom Icons, Is there a way to make custom icons that support ligatures? Here is my current code snippet: app.component.ts import { Component } from &ap ...

Steps for updating the value of a button in Typescript and React

I currently have a button that manages my language switcher, configured to handle cookies, URL changes, and now I want it to update the translations on the page as well. The <img> tag is utilized for changing the country flag. < ...

What is the significance of an equals sign being located within the angle brackets of a type parameter?

Within the type definitions for Bluebird promises, there is a catch function that has the following definition: catch<U = R>(onReject: ((error: any) => Resolvable<U>) | undefined | null): Bluebird<U | R>; The symbol "R" is derived fr ...

Employing Multer and Express in conjunction with TypeScript

Overview Currently, I am working on a project that involves creating a user-friendly website where individuals can easily upload images. For this particular task, I have employed Node.js, React, Multer, and Typescript. Issue at Hand app.post('/admi ...

Transferring information via Segments in Ionic 3

I'm facing a challenge where I need to transfer a single ion-card from the "drafts" segment to the "sent" segment by simply clicking a button. However, I am unsure of how to achieve this task seamlessly. Check out this image for reference. ...

I'm having trouble retrieving the object value from a different function within my Typescript and Express application

Currently I am experimenting with utilizing typescript alongside express for my application development. I have created a function that I intend to utilize in various sections of my codebase. Upon invoking the function, I am able to observe the values thro ...

Dispatch a websocket communication from a synchronous function and retrieve the information within the function itself

I am currently working on an Angular project and need guidance on the most effective approach to implement the following. The requirement is: To retrieve an image from the cache if available, otherwise fetch it from a web socket server. I have managed ...

Are you encountering issues with Google Analytics performance on your Aurelia TypeScript project?

I recently started using Google Analytics and I am looking to integrate it into a website that I'm currently building. Current scenario Initially, I added the Google Analytics tracking code to my index.ejs file. Here is how the code looks: <!DOC ...

Guide to connecting data from the backend to the frontend in the select option feature using Angular 9

I have a backend system where I store a number representing a selected object, which I am trying to display in a select option using Angular. Currently, the select option only displays a list of items that I have predefined in my TypeScript code using enu ...

Strange Node.js: I always avoid utilizing `require()`, yet encountered an unexpected error

For more information on this particular issue, please refer to this link It's quite puzzling as I haven't used the require() function in my code, yet I'm receiving an error telling me not to use it. How odd! The problematic code snippet i ...

Incorporating a TypeScript module into a JavaScript module within a React application

I'm encountering an issue with my React app that was created using create-react-app. I recently added a Typescript module to the project, which is necessary for functionality reasons. Although it will remain in Typescript, I made sure to install all t ...

Experiencing TypeScript error in VSCode while trying to run in Nodejs? Here's how to troubleshoot and resolve

Experimenting with the performance measurement code provided by Nodejs in VSCode has been an interesting challenge for me. I encountered no issues running the code in Nodejs, and it executed smoothly. However, when attempting to run the code in VSCode, er ...