My api is working absolutely fine everywhere except when I try to do an if block for a potential Axios error. This is because the status
is in response.response.status
instead of response.status
so Typescript throw the error Property 'response' does not exist on type 'AxiosResponse<any, any>'.
Can anyone help me with this?
Working with no AxiosError present:
postBoundary: async (boundary: CreateBoundary) => {
const response = await axios.post(
`${config.baseApiPath}boundary`,
boundary
);
return response.data; //returns correctly
}
Not working with Axios Error present:
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;
}
This is because when an Axios request fails, the error object has a different structure than a successful response.
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;
}
}