簡體   English   中英

嘗試和捕獲塊 Typescript 中的類型“錯誤”上不存在屬性“響應”

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

我是 typescript 的新手,我正在嘗試處理 axios 獲取中的錯誤,但是在作為 JSON 響應的響應中,我無法正確處理它。

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

要獲得正確的類型,您可以添加檢查錯誤是否是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)
    }
  }
}

GitHub 問題包含更多建議。

TypeScript操場

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM