Reputation: 549
I am new to typescript, I am trying to handle errors in axios fetch, but in the response which comes as a JSON response, I am not able to handle it correctly.
try {
await axios_auth.put(`${"http://localhost:4500/api" + API_CALL}`, values).then((res) => {
console.log(res.data.success)
})
} catch (err: any) {
if (err instanceof Error) {
if (err.response.status === 400 && err.response.data.code === "CATEGORY_ALREADY_EXIST") { // Property 'response' does not exist on type 'Error'.
console.log("Category exists")
}
} else {
console.log('Unexpected error', err);
}
}
Upvotes: 1
Views: 9054
Reputation: 15106
To get the correct types, you can add a check whether the error is an instance of the AxiosError
class:
import { AxiosError } from 'axios'
..
try {
// ..
} catch (err: unknown) {
if (err instanceof AxiosError) {
if (
err.response?.status === 400 &&
err.response?.data.code === 'CATEGORY_ALREADY_EXIST'
) {
console.log('Category exists')
}
} else {
console.log('Unexpected error', err)
}
}
}
This GitHub issue contains a few more suggestions.
Upvotes: 4