axios 打字稿错误,注释必须是“任何”或“未知”,如果?

Fay*_*hen 37 javascript typescript axios

我得到的错误是Catch clause variable type annotation must be 'any' or 'unknown' if specified.ts(1196)

用下面的代码

import axios, { AxiosError } from "axios";
try {
        
    } catch(error: AxiosError) {
      throw Error(error);
    }
Run Code Online (Sandbox Code Playgroud)

如何在TS中抛出axios错误?

Max*_*Max 54

我建议您删除如下错误类型:

import axios from 'axios';

try {
  // do what you want with axios
  // axios.get('https://example.com/some-api');
} catch (error) {
  // check if the error was thrown from axios
  if (axios.isAxiosError(error)) {
    // do something
    // or just re-throw the error
    throw error;
  } else {
    // do something else
    // or creating a new error
    throw new Error('different error than axios');
  }
}
Run Code Online (Sandbox Code Playgroud)

我刚刚为它创建了一个stackblitz 。如果您想更深入地了解,请查看这篇文章

  • 这与打字稿中的工作方式完全一样:)如果不适合你,请上传你的“tsconfig.json”,然后我会看看它 (3认同)
  • 由于 StackOverflow 不是聊天论坛,如果您需要某人的帮助,我建议您上传重现错误所需的所有内容。否则,人们无法帮助你。上面的代码实际上是打字稿代码并且在我这边工作。 (3认同)

Sha*_*een 51

使用 AxiosError 来转换错误

import  { AxiosError } from 'axios';

catch (error) {
  const err = error as AxiosError
  console.log(err.response?.data)
}
Run Code Online (Sandbox Code Playgroud)

  • 选角可能会失败?如果演员失败会发生什么? (7认同)

nei*_*eil 12

您不能在打字稿中为 catch 子句变量编写特定的注释,这是因为在 javascript 中,catch 子句将捕获引发的任何异常,而不仅仅是指定类型的异常。

在打字稿中,如果您只想捕获特定类型的异常,则必须捕获抛出的任何内容,检查它是否是您想要处理的异常类型,如果不是,则再次抛出它。

含义:在执行任何操作之前,首先检查抛出的错误是否为 axios 错误。

try {
// do something
}catch (err) {
     // check if error is an axios error
     if (axios.isAxiosError(err)) {
                
      // console.log(err.response?.data)
      if (!err?.response) {
          console.log("No Server Response");
       } else if (err.response?.status === 400) {
         console.log("Missing Username or Password");
       } else if (err.response?.status === 401) {
         console.log("Unauthorized");
        } else {
        console.log("Login Failed");
      } 
   } 
}

Run Code Online (Sandbox Code Playgroud)


Yas*_*kar 5

该错误可以是任何类型,更安全的捕获方法是

try {
   // TODO :: API call
} catch (err) {
   if (error instanceof AxiosError) {
       // TODO :: handle it here
   } else {
      throw err
   }
}
Run Code Online (Sandbox Code Playgroud)