Skip to content

Commit

Permalink
fix(Reducer errors): log exceptions thrown from store.dispatch insi…
Browse files Browse the repository at this point in the history
…de the middleware (#379)

Closes #263

Most often this is caused by exceptions in your reducers. Right now due to a bug in rxjs these errors can sometimes (but not always) be silently swallowed. This works around it by catching them ourselves and logging and logging them.
  • Loading branch information
Jerry-Hong authored and jayphelps committed Dec 5, 2017
1 parent e850c93 commit 56c1903
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
8 changes: 7 additions & 1 deletion src/createEpicMiddleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,13 @@ export function createEpicMiddleware(rootEpic, options = defaultOptions) {
return output$;
})
::switchMap(output$ => options.adapter.output(output$))
.subscribe(store.dispatch);
.subscribe(action => {
try {
store.dispatch(action);
} catch (err) {
console.error(err);
}
});

// Setup initial root epic
epic$.next(rootEpic);
Expand Down
26 changes: 25 additions & 1 deletion test/createEpicMiddleware-spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,31 @@ describe('createEpicMiddleware', () => {
]);
});

it('should throw if you don\'t provide a rootEpic', () => {
it('should console error when reducer throw exception', () => {
sinon.spy(console, 'error');

const reducer = (state = [], action) => {
switch (action.type) {
case 'ACTION_1':
throw new Error();
default:
return state;
}
};
const epic = (action$, store) =>
mergeStatic(
action$.ofType('FIRE_1')::mapTo({ type: 'ACTION_1' }),
action$.ofType('FIRE_2')::mapTo({ type: 'ACTION_2' })
);
const middleware = createEpicMiddleware(epic);
const store = createStore(reducer, applyMiddleware(middleware));

store.dispatch({ type: 'FIRE_1' });
expect(console.error.callCount).to.equal(1);
console.error.restore();
});

it("should throw if you don't provide a rootEpic", () => {
expect(() => {
createEpicMiddleware();
}).to.throw('You must provide a root Epic to createEpicMiddleware');
Expand Down

0 comments on commit 56c1903

Please sign in to comment.