0

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))
    }
}

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

11 Comments

Sorry, I'm a total newbie, but where can I get the error field from the hasMessage function?
Oh sorry, typo. Should be e.message. Let me fix it.
I just tried this, but when the developer tool is open, it still crashes
You never mentioned any crash. Maybe add that to your question, with the full error message? This shouldn't have anything to do with crashing behaviour though
I'm sorry, I've corrected the description
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.