Search code examples
reactjstypescriptaxiostry-catchredux-toolkit

Can't catch typescript error in typescript


I can't catch the error. I deliberately messed up the query string to handle this case, but it still gets through. With developer tools open, the app crashes. I am using axios, redux-toolkit and typescript. Please tell me what should I do?

export const fetchUsers = createAsyncThunk(
    'user/fetchAll',
    async (_, {rejectWithValue}) => {
        try {
            const response = await axios.get<IUser[]>('https://jsonplaceholder.typicode.com/use2rs')
            return response.data
        } catch (e) {
            if (e instanceof Error) {
                return rejectWithValue(e.message)
            }

        }
    }
)

But when I use such a tool, everything works well. However, I'd like to use the convenience of createAsyncThunk and rejectWithValue


export const fetchUsers = () => async (dispatch: AppDispatch) => {
    try {
        dispatch(userSlice.actions.usersFetching())
        const response = await axios.get<IUser[]>('https://jsonplaceholder.typicode.com/users')
        dispatch(userSlice.actions.usersFetchingSuccess(response.data))
    } catch (e: any) {
        dispatch(userSlice.actions.usersFetchingError(e.message))
    }
}

Solution

  • instanceof Error almost never works, since extending JavaScript-internal classes like Error can result in classes that technically do not keep the right property chain. This might differ depending on your transpilation target.

    Better check something like typeof error.message == 'string' or write a little typeguard:

    function hasMessage(e: any): e is {message: string} {
      return e && typeof e.message == 'string'
    }
    
    // ...
    
    if (hasMessage(e)) return rejectWithValue(e.message)