简体   繁体   中英

Property 'response' does not exist on type 'Error' in try and catch block Typescript

I am new to typescript, I am trying to handle errors in axios fetch, but in the response which comes as a JSON response, I am not able to handle it correctly.

try {
    await axios_auth.put(`${"http://localhost:4500/api" + API_CALL}`, values).then((res) => {

        console.log(res.data.success)
    })


  
} catch (err: any) {
    if (err instanceof Error) {
    

        if (err.response.status === 400 && err.response.data.code === "CATEGORY_ALREADY_EXIST") { // Property 'response' does not exist on type 'Error'.
            console.log("Category exists")
        }
        

    } else {
        console.log('Unexpected error', err);
    }
}

To get the correct types, you can add a check whether the error is an instance of the AxiosError class:

import { AxiosError } from 'axios' 

..

try {
    // ..
  } catch (err: unknown) {
    if (err instanceof AxiosError) {
      if (
        err.response?.status === 400 &&
        err.response?.data.code === 'CATEGORY_ALREADY_EXIST'
      ) {
        console.log('Category exists')
      }
    } else {
      console.log('Unexpected error', err)
    }
  }
}

This GitHub issue contains a few more suggestions.

TypeScript playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM