我得到了错误
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);
}
如何在TS中抛出axios错误?
我建议您删除如下错误类型:
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');
}
}
我刚刚为其创建了一个 stackblitz。 如果您想更深入地了解,请看这篇文章
使用AxiosError来投射错误
import { AxiosError } from 'axios';
catch (error) {
const err = error as AxiosError
console.log(err.response?.data)
}
您不能在打字稿中为 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");
}
}
}
错误可以是任何类型,更安全的捕获方法是
try {
// TODO :: API call
} catch (err) {
if (error instanceof AxiosError) {
// TODO :: handle it here
} else {
throw err
}
}
您将异常设置为
unknown
,如下所示: catch (err: unknown)
然后您可以使用 instanceOf
来识别错误:
import { AxiosError } from 'axios'
...
function getTheAwesome () {
try {
// This is some method I need to call
foo()
// My axios client call
await axios.get('/awesome')
// This method can also throw an error
await bar()
} catch (err: unknown) {
if (err instanceOf AxiosError) {
// Handle the axios error
// You can get the error response like this:
if (err.response?.data) {
const errorResponse = err.response.data as MyErrorResponse
}
} else if (err instanceOf SomeOtherError) {
// Handle the other errors that you expect from your other methods
} else {
// Handle everything else
}
}
}
catch (error) {
const err:any=error;
alert(err.response.data)
}
它对我有用:)