Skip to content

Commit

Permalink
feat: Implement axios error type (#145)
Browse files Browse the repository at this point in the history
  • Loading branch information
Atiqur Rahman authored Apr 21, 2022
1 parent a268a68 commit 1712ae7
Showing 1 changed file with 20 additions and 3 deletions.
23 changes: 20 additions & 3 deletions src/redux/api.thunk.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,26 @@
import { createAsyncThunk } from "@reduxjs/toolkit";
import { AxiosResponse } from "axios";
import { AxiosError, AxiosPromise } from "axios";

export type ErrorType<Error> = AxiosError<Error>;

export const errorHandler = <TError = Error>(error: ErrorType<TError>) => {
const { request, response } = error;
if (response) {
// process error to based on type
const message = response.data;
return message;
}
if (request) {
// request sent but no response received
return "network.noInternet";
}
// Something happened in setting up the request that triggered an Error
return "network.unknown";
};

export function createApiAsyncThunk<Result, Arg>(
key: string,
action: (arg: Arg) => Promise<AxiosResponse<Result>>
action: (arg: Arg) => AxiosPromise<Result>
) {
return createAsyncThunk<Result, Arg>(
key,
Expand All @@ -13,7 +30,7 @@ export function createApiAsyncThunk<Result, Arg>(

return data;
} catch (error) {
return rejectWithValue(error.response.data);
return rejectWithValue(errorHandler(error));
}
}
);
Expand Down

0 comments on commit 1712ae7

Please sign in to comment.