question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Throw error on rejection

See original GitHub issue

Hi, I’m migrating my application from redux-thunk + redux-promise-middleware to redux-toolkit.

I have a problem that I cannot solve that concerns throwing the error in an asynchronous action.

The main difference with redux-promise-middleware is that if an error is generated in an asynchronous action, it dispatches the failed action and at the same time does not stop the error throw. On the redux-toolkit instead the action is only rejected. Reading the various issues on redux-toolkit, I deduced that adding the serializeError option and throwing the error, I did also receive the error on the dispatch of the action, however the reject action is not performed.

I’m going to write some code to explain the context:

class PostContainer extends React.Component {
  public componentDidMount() {
    try {
      this.props.preload();
    } catch(err) {
      console.log(err);
      // i'd like to receive here the error
    }
  }
}

const mapDispatchToProps = (dispatch: any) => ({
  preload() {
    await dispatch(preload());
    dispatch(somethingelse())
  }
});

export default connect(null, mapDispatchToProps)(PostContainer);

// action
const preload = createAsyncThunk('post/preload', async (_: void, { dispatch }) => {
  // if one of this two action throw an error
  await dispatch(getPosts());
  await dispatch(getUsers());
});

expost const postSlice = createSlice({
  name: 'post',
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    // i'd like to receive the rejected action
    builder.addCase(prealod.rejected, (state, action) => {
      return {
        ...state,
        isError: true
      }
    })
  }
})

Is there a way to achieve this with redux-toolkit? Maybe should i use the unwrapResult utility? If this is the case, how can i implement in this scenario? Thanks for you time.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:1
  • Comments:8 (1 by maintainers)

github_iconTop GitHub Comments

3reactions
triboucommented, Mar 17, 2021

Thank you for that input. I agree that would be an unwanted case to have to add to RTK.

I did find a solution that restores my expected use case of 1) throwing errors by default after dispatching rejections and 2) ignoring ConditionError–appending this middleware after the RTK default middleware:

import { Middleware } from "@reduxjs/toolkit";

export const throwMiddleware: Middleware = () => (next) => (action) => {
  next(action);
  if (action?.error) {
    throw action.error;
  }
};

With this in place, I no longer need to .then(unwrapResult) everywhere which, in turn, ignores ConditionErrors.

1reaction
markeriksoncommented, Feb 25, 2021

Agreed that it’s not terribly pretty if you have to add that in a bunch of spots.

FWIW, these threads have prior discussion on the topic: #734, #775 , and #792 . In particular, #792 has a lot of design discussion related to this, such as https://github.com/reduxjs/redux-toolkit/pull/792#issuecomment-722710316 .

Read more comments on GitHub >

github_iconTop Results From Across the Web

Error handling with promises - The Modern JavaScript Tutorial
In the task an error is thrown form inside the promise and promise is never settled neither with a resolve nor reject. The...
Read more >
JavaScript Promises - reject vs. throw - Stack Overflow
My understanding is that if an error bubbles up from an asynchronous callback, throw will cause the error to be handled even if...
Read more >
Reject Vs Throw Promises in JavaScript - GeeksforGeeks
3. The reject can only be used with a Javascript promise but throw unlike reject can be used to create and throw user-defined...
Read more >
Promise.reject() - JavaScript - MDN Web Docs
The static Promise.reject function returns a Promise that is rejected. For debugging purposes and selective error catching, it is useful to ...
Read more >
prefer-promise-reject-errors - Pluggable JavaScript Linter
It is considered good practice to only pass instances of the built-in Error object to the reject() function for user-defined errors in Promises....
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found