Search code examples
angulartypescripterror-handlingngrxngrx-store

how to implement error handling on store in Angular


I'm working on existing codebase and my task is to implement error handling in my update Chart but not really sure how to implement correctly since I'm using store management so I would be really appreciated if I can get any suggestion or help on how I should implement error handling in store.

I did something like this and tested it by providing to the wrong api route in my ChartService.ts file but I didn't get the error message and it always saying it "has been saved" no matter if I give the right api route or wrong api route for updating chart.

The problem I have right now is, It's not giving me error snackbar message even when there is errors in api or network.

import {Store} from '@ngrx/store';

  saveClick(){
    try
    {
      this.store.dispatch(updateChart({chart: this.chart}));
      this.snackbar.open("Changes to \"" + this.chart.name + "\" has been saved", "", { duration: 2500 });
    }
    catch(error)
    {
      this.snackbar.open("Error has occurred. Could not update Chart", "", { duration: 2500 });
    }
  }

Chart.effets.ts

    updateChart$ = createEffect(() => this.actions$.pipe(
        ofType(ChartActionTypes.UpdateChart),
        exhaustMap((props: { chart: Chart }) => this.chartService.updateChart(props.chart)//this.getChart(props)
            .pipe(
                // tap(c => console.log('TAPPY TAP', c)),
                map(chart => {
                    return chartLoaded({ chart: chart })
                }),
                catchError(() => EMPTY)
            ),
        )
    )
    )

HTML

    <button color="primary" mat-flat-button (click)="saveClick()" [disabled]="this.chart.isPublished">Save</button>

It's not gonna run on but I uploaded all the code for this component in stackblitz hoping someone can help me by looking at the code. thanks https://stackblitz.com/edit/angular-ivy-ncbmb4


Solution

  • You are pretty close:

    • Your dispatch of update is fine
    • Your chartLoaded is fine
    • Your catchError is wrong

    Notice the way you dispatched an action to update your store with the new data, you need to do the same when you get an error.

    catchError((error: any, effect: Observable<Action>) => effect.pipe(startWith(chartUpdateError({ error }))))
    

    So this new action is going to set the error in the store using the reducer. Now to know if an error happened, you need a selector that check for what you just updated in your store which means your saveClick() doesnt handle any of that. You either subscribe to the selector in your ts file or in your html depending on what you are looking to do. I cant really help you with the syntax because I dont know what your reducer/action/selector look like.