Intercepting errors with Angular and NgRx

Using NgRx for state management has been a great way to store server data across an application. One thing I started to wonder is how could I use this same pattern, but in a different manner to make components even more useful and clean. Luckily, I was just finishing up making some Angular Reactive Forms and needed a way to handle the server errors that came back.

Granted errors are not technically a form of data that I want persisted across the application, but the ease of use of dispatching events that components were subscribed to seemed to fit this need.

Below is a recipe that I came up with to intercept errors from the server, store them in the store, and have a reusable component subscribe to and display the errors.

Please note: The examples below assume you have a base understanding of the use case of NgRx and that you already have state management setup for your application.

A great reference book that goes deeper into this topic: Architecting Angular Applications with Redux, RxJS, and NgRx

State management

In order for this all to work properly, I am choosing to utilize NgRx to handle the state management of the errors. This allows me to dispatch events to the store and utilize the reducers to hold onto the errors for areas of the application that are subscribed to the store selectors.

Generating a state setup for this purpose is pretty straight forward and so is its corresponding selector:

1
2
3
4
5
6
7
8
// form-errors.state.ts
export interface IFormErrorsState {
formErrors: any;
}

export const initialFormErrorsState: IFormErrorsState = {
formErrors: null,
};
1
2
3
4
5
6
7
// form-errors.selector.ts
const selectFormErrorsState = (state: IAppState) => state.formErrors;

export const selectFormErrors = createSelector(
selectFormErrorsState,
(state: IFormErrorsState) => state.formErrors
);

The actions

In this case, I need two actions. One to add the errors that are intercepted and a second to clear out the errors. Clearing out the errors is important so that the state of errors does not stay around for other subscribers to pick up. My current application is very single page-esque, so right now there is no sharing of the same component on a given page.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// form-errors.actions.ts
export enum EFormErrorsActions {
AddErrors = 'ADD_ERRORS',
ClearErrors = 'CLEAR_ERRORS',
}

export class AddErrors implements Action {
public readonly type = EFormErrorsActions.AddErrors;
constructor(public payload: ServerErrors[]) { }
}

export class ClearErrors implements Action {
public readonly type = EFormErrorsActions.ClearErrors;
}

export type FormErrorsActions =
| AddErrors
| ClearErrors;

The reducers

Reducing the data received is also pretty simple. We are just storing the data when we get the action to AddErrors and then subsequently nulling out the state when the ClearErrors action is received.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// form-errors.reducers.ts
export const formErrorsReducers = (
state = initialFormErrorsState,
action: FormErrorsActions,
): IFormErrorsState => {
switch (action.type) {
case EFormErrorsActions.AddErrors: {
return {
...state,
formErrors: action.payload,
};
}
case EFormErrorsActions.ClearErrors: {
return {
...state,
formErrors: null,
};
}
default:
return state;
}
};

Intercepting the errors

Angular makes it simple to setup interceptors and watch responses that come back from a server or even watching for requests. I wrote about one a while ago on adding headers to a request, Angular HTTP interceptors, making development DRY. In this case, I am going to intercept the response for errors that come back.

To do this, we create an interceptor that does one thing, catchError from the RxJS operator library.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(
private store: Store<IAppState>,
) { }

intercept(
req: HttpRequest<any>,
next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
catchError((response: HttpErrorResponse) => {
if ([401, 422].includes(response.status)) {
this.store.dispatch(new AddErrors(response.error));
}
return of(response.error);
})
);
}
}

Currently, there are two error codes I am looking for: 401 and 422. I could also throw in 500 here, but my current use case is around form submission errors.

When the intercept happens, I call to the store, dispatching the action to add the received errors to the store.

In order to not lock up the application, I make sure to continue on the response of the errors as an observable to the next handler.

Creating the reusable component

Now the final part that glues all of this together and makes things very reusable from form to form; creating a component that observes for these store changes and subsequently displays them.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// server.component.ts
@Component({
selector: 'app-server-errors',
templateUrl: './server.component.html',
styleUrls: ['./server.component.scss']
})
export class ServerErrorsComponent implements OnDestroy {
public errors$: Observable<any> =
this.store.select(selectFormErrors);

constructor(
private store: Store<IAppState>,
) { }

ngOnDestroy() {
this.store.dispatch(new ClearErrors());
}
}
1
2
3
4
5
6
7
8
// server.component.html
<div *ngIf="errors$ | async as errors">
<ul>
<li *ngFor="let error of errors">
{ { error } }
</li>
</ul>
</div>

When this component is created, it starts to observe from the store through the errors selector. This allows the template to display them when it receives them.

The other important part of this component is that it dispatches the ClearErrors action to the store when the component gets destroyed. This makes sure that other components that may be subscribed to the error state do not display the same errors.

Lots of possibilities

I am finding the use of NgRx super powerful as I add more things to an application I have been working on. With it in conjunction of RxJS, the patterns seem endless in making development very straight forward. I am looking forward to uncovering other use cases to apply the knowledge I have gained in working with Angular, NgRx, and RxJS.

Filed under: Code