New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How to type axios error in Typescript? #3612
Comments
@EkeMinusYou This is a great question. If you look at the types you'll see that
This is a newer feature, so I suggest you update to the newest version of Axios to ensure it is present. |
@timemachine3030 It looks good. Thank you! |
just in case this helps anyone else I created some middleware based on this answer to make the code a bit cleaner in the eventual request: import axios, { AxiosError } from 'axios';
interface IErrorBase<T> {
error: Error | AxiosError<T>;
type: 'axios-error' | 'stock-error';
}
interface IAxiosError<T> extends IErrorBase<T> {
error: AxiosError<T>;
type: 'axios-error';
}
interface IStockError<T> extends IErrorBase<T> {
error: Error;
type: 'stock-error';
}
export function axiosErrorHandler<T>(
callback: (err: IAxiosError<T> | IStockError<T>) => void
) {
return (error: Error | AxiosError<T>) => {
if (axios.isAxiosError(error)) {
callback({
error: error,
type: 'axios-error'
});
} else {
callback({
error: error,
type: 'stock-error'
});
}
};
} Then the code looks like: .catch(
axiosErrorHandler<MyType>(res => {
if (res.type === 'axios-error') {
//type is available here
const error = res.error;
} else {
//stock error
}
})
); |
I have a scenario where the error response is different than the successful response and I'm trying to figure out what's the best way to type it. import request from "axios";
type TodoSuccessResponse = {
userId: number;
id: number;
title: string;
completed: boolean;
};
type TodoErrorResponse = {
error: string;
};
async function main() {
try {
const res = await request.get<TodoSuccessResponse>(
"https://jsonplaceholder.typicode.com/todos/1"
);
console.log(res.data.id);
} catch (err) {
if (request.isAxiosError(err) && err.response) {
// Is this the correct way?
console.log((err.response?.data as TodoErrorResponse).error);
}
}
} |
It worked for me: try {
// statements
} catch(err) {
const errors = err as Error | AxiosError;
if(!axios.isAxiosError(error)){
// do whatever you want with native error
}
// do what you want with your axios error
} |
You can then use it to get fully-typed error response data:
|
I am having a little problem understanding this. |
I'd guess that this is useful in the case of known/expected types of Axios errors. For example, I use the following to provide type info to Laravel validation error responses (always status code interface LaravelValidationResponse extends AxiosResponse {
status: 422;
data: {
message: string;
errors: Record<string, Array<string>>;
};
}
export interface LaravelValidationError extends AxiosError {
response: LaravelValidationResponse;
}
function axiosResponseIsLaravelValidationResponse(response: AxiosResponse): response is LaravelValidationResponse {
return response.status === 422
&& typeof response.data?.message === 'string'
&& typeof response.data?.errors === 'object';
}
export function isLaravelValidationError(error: unknown): error is LaravelValidationError {
return Boolean(
axios.isAxiosError(error)
&& error.response
&& axiosResponseIsLaravelValidationResponse(error.response)
);
} While I probably wouldn't go with @btraut's approach as it doesn't allow for differentiating between different types of errors, it could be useful as a quick type cast. |
This is fantastic and very helpful. Thank you very much 🙏🏾 |
Hi there @timemachine3030, |
Revisiting this after a year for learning more about ts/js I would rewrite it as: .catch((err: unknown) {
if (axios.isAxiosError(error)) {
// Access to config, request, and response
} else if (err instanceof Error) {
// Just a stock error
} else {
// unknown
}
}) Assuming errors are of created by The browser and node.js can throw native errors that don't extend the |
my error interface. interface Error {
message: string[];
statusCode: number;
} my catch error. try {
} catch (err) {
const error = err as AxiosError<Error>;
console.log(error.response?.data.message);
} |
To identify an |
Looks like i need to upgrade axios package |
I would love something more concise, like |
If you don't mind adding another dependency to your project, the axios-hooks module has some types and interfaces that do just that:
Just call the Good luck |
` try {
` |
Describe the issue
I have question how type axios error in Typescript.
I know
AxiosError
type is exposed, but I don't think it should be used because it's unclear if it's an Axios Error when caught.Example Code
Should I do something judgement before typing with AxiosError?
Please tell me a good practice.
Expected behavior, if applicable
A clear and concise description of what you expected to happen.
Environment
Additional context/Screenshots
Add any other context about the problem here. If applicable, add screenshots to help explain.
The text was updated successfully, but these errors were encountered: