diff --git a/src/redux/api.thunk.ts b/src/redux/api.thunk.ts index a6aab09..7f9303e 100644 --- a/src/redux/api.thunk.ts +++ b/src/redux/api.thunk.ts @@ -1,9 +1,26 @@ import { createAsyncThunk } from "@reduxjs/toolkit"; -import { AxiosResponse } from "axios"; +import { AxiosError, AxiosPromise } from "axios"; + +export type ErrorType = AxiosError; + +export const errorHandler = (error: ErrorType) => { + 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( key: string, - action: (arg: Arg) => Promise> + action: (arg: Arg) => AxiosPromise ) { return createAsyncThunk( key, @@ -13,7 +30,7 @@ export function createApiAsyncThunk( return data; } catch (error) { - return rejectWithValue(error.response.data); + return rejectWithValue(errorHandler(error)); } } );