You cannot write a specific annotation for the catch clause variable in typescript, this is because in javascript a catch clause will catch any exception that is thrown, not just exceptions of a specified type.
In typescript, if you want to catch just a specific type of exception, you have to catch whatever is thrown, check if it is the type of exception you want to handle, and if not, throw it again.
meaning: make sure the error that is thrown is an axios error first, before doing anything.
solution 1
using type assertion
Use AxiosError to cast error
import { AxiosError } from 'axios';
try {
// do some api fetch
} catch (error) {
const err = error as AxiosError
// 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 {
console.log("Login Failed");
}
}
solution 2
check if the error is an axios error first, before doing anything
import axios from "axios"
try {
// do something
} catch (err) {
// check if the 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 {
console.log("Login Failed");
}
}
}