How to handle errors inside reducers?

冷暖自知 提交于 2019-12-07 16:23:08

问题


I've my loggerService and I need to catch all errors in reducer and send it via my service to the server.

How can I do it? I know that reducer should be a pure function, but still any ideas?

I need to add in reduser try catch

    case actions.GAMES_LOADED{
       ......
       try{}
       catch(err){
       this.loggerService.error(err);
    }
}

Or maybe throw something in reducer and catch it in some place...

Thanks a lot


回答1:


Short answer: You don't.

Why? - The reducer is only responsible for updating the store, it should not perform any business-logic or validate data - any data that reaches the store should be already valid and just be stored/updated/removed from the store.

Possible solution: You should do these kind of operations either in an effect or in some service that is responsible for fetching/creating the data.




回答2:


I don't agree that reducer is only responsible for updating the store. It is rather responsible for updating application state..store as well as UI state. So in this case there is a valid responsibility for the reducer to update error state in the application. Upon redirection from effect on error by some error action reducer can update error state. However in that case same reducer should wipe out error state upon receiving any success action. But I am not suggesting that this is best practice.




回答3:


If you add to your application state a "loadingMessage" item, you can set that state in this reducer to empty or a message. This can then be read by a component using a store selector and if not empty, logged or a dialog produced or whatever you wish to do with this state.



来源:https://stackoverflow.com/questions/41445082/how-to-handle-errors-inside-reducers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!