Error Handling Middleware in Redux v5.0.0
Show how to write a middleware that centralizes error handling for Redux actions in the context of Redux v5.0.0.
import { applyMiddleware, createStore } from 'redux';
// Define your action types
const RAISE_ERROR = 'RAISE_ERROR';
// Example error action
const raiseError = (error) => ({
type: RAISE_ERROR,
error
});
// Reducer
const rootReducer = (state = {}, action) => {
switch(action.type) {
case RAISE_ERROR:
// Handle error state update
return { ...state, lastError: action.error };
default:
return state;
}
};
// Error handling middleware
const errorHandlingMiddleware = (store) => (next) => (action) => {
try {
// Pass action to next middleware or reducer
return next(action);
} catch (error) {
// Handle the error by dispatching an error action
console.error('Caught an exception!', error);
store.dispatch(raiseError(error));
}
};
// Create store with middleware
const store = createStore(
rootReducer,
applyMiddleware(errorHandlingMiddleware)
);
The code provides a Redux middleware 'errorHandlingMiddleware' that catches JavaScript errors in the process of dispatching actions and passing them through the reducers or subsequent middleware. When an error occurs, it logs the error and dispatches an 'RAISE_ERROR' action to store the error information in the Redux state, which can be used to inform the user or for debugging.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Error Handling in Redux</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/5.0.0/redux.min.js"></script>
</head>
<body>
<script src="app.js"></script> <!-- app.js contains the Redux setup including the error handling middleware -->
</body>
</html>
This HTML document includes the necessary Redux library and references the external JavaScript file 'app.js' where the Redux store setup with error handling middleware is located. This middleware will catch and handle errors thrown during Redux action dispatches.