Redux—global error handler -
i running redux on node. handle asynchronous actions, reading file or listing of directory, using redux-thunk
in combination promises. typical action can that:
const fs = require('fs'), { promisify } = require('util'), readdir = promisify(fs.readdir); const listfiles = dir => dispatch => readdir(dir) .then(files => dispatch({ type: '…', payload: { files } }));
so:
try { store.dispatch(listfiles('/some/path')); catch (error) { //some rescue plan here, //won't work if directory not exists }
wont work here, because action asynchronous , right now, way see handle errors add .catch()
promises in actions , dispatch error action there.
that has 2 downsides:
- a lot of code repetition and
- i need know possible errors in ahead.
so question is: there way create global error handler, called if asynchronous action fails, such can add error indicating information state, can displayed?
could possible »storeenhancer« or »middleware«?
update
i find helpful:
process.on('unhandledrejection', (reason, promise) => { console.log(reason.message); });
that callback triggered whenever promise rejected , no catch block added. right seams trick, anyway, prefer solution exact same thing, rejected promises triggered within store.dispatch()
, when error within processing of actions/middleware/reducers within redux comes happen.
if you're looking redux middleware solution, take @ redux-catch
.
Comments
Post a Comment