Error Actions: Standardizing Failure Cases
What you'll learn: How to consistently handle errors in your reducer by using dedicated error action types or error flags.
When actions can fail (like async operations, validations, or network requests), you need a standard way to communicate failures to your reducer. There are two common patterns:
Pattern 1: Boolean Flag
Include an error boolean and error details in the action:
dispatch({
type: 'LOGIN_COMPLETE',
error: true,
payload: { message: 'Invalid credentials' }
});
Your reducer checks the flag:
switch (action.type) {
case 'LOGIN_COMPLETE':
if (action.error) {
return { ...state, errorMessage: action.payload.message };
}
return { ...state, user: action.payload };
}
Pattern 2: Separate Error Actions
Create distinct action types for failures:
// Success
dispatch({ type: 'LOGIN_SUCCESS', payload: userData });
// Failure
dispatch({ type: 'LOGIN_ERROR', payload: { message: 'Invalid credentials' } });
switch (action.type) {
case 'LOGIN_SUCCESS':
return { ...state, user: action.payload, error: null };
case 'LOGIN_ERROR':
return { ...state, error: action.payload.message };
}
The Analogy: Think of error handling like a package delivery system. Pattern 1 is like marking a package "FAILED" with a note attached. Pattern 2 is like routing failed packages to a completely different processing center. Both work, but Pattern 2 makes it clearer what happened at a glance.
Most teams prefer Pattern 2 because it makes state transitions explicit and easier to track in debugging tools.
Key Takeaway: Standardize error handling in your reducers by either adding an error boolean to actions or creating separate _ERROR action types—consistency makes your state logic predictable and maintainable.