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 。如果您想更深入地了解,请查看这篇文章
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)
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)
该错误可以是任何类型,更安全的捕获方法是
try {
// TODO :: API call
} catch (err) {
if (error instanceof AxiosError) {
// TODO :: handle it here
} else {
throw err
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
59974 次 |
| 最近记录: |