我的 api 在任何地方都工作得绝对正常,除非我尝试对潜在的 Axios 错误执行 if 块。这是因为
status
位于 response.response.status
而不是 response.status
,所以 Typescript 会抛出错误 Property 'response' does not exist on type 'AxiosResponse<any, any>'.
有人可以帮我吗?
在不存在 AxiosError 的情况下工作:
postBoundary: async (boundary: CreateBoundary) => {
const response = await axios.post(
`${config.baseApiPath}boundary`,
boundary
);
return response.data; //returns correctly
}
无法使用 Axios 出现错误:
postBoundary: async (boundary: CreateBoundary) => {
const response = await axios.post(
`${config.baseApiPath}boundary`,
boundary
);
// when response has an Axios error response.status
// doesn't exist because there are two nested responses
if (response.response.status ===
HttpStatusCode.PayloadTooLarge) {
throw new Error("Error");
}
return response.data;
}
这是因为当 Axios 请求失败时,错误对象的结构与成功响应的结构不同。
import { AxiosError, HttpStatusCode } from 'axios';
postBoundary: async (boundary: CreateBoundary) => {
try {
const response = await axios.post(
`${config.baseApiPath}boundary`,
boundary
);
return response.data;
} catch (error) {
// First check if it's an AxiosError
if (error instanceof AxiosError) {
// Now we can safely access error.response
if (error.response?.status === HttpStatusCode.PayloadTooLarge) {
throw new Error("Payload too large");
}
}
// Re-throw any other errors
throw error;
}
}