ngrxngrx-effects

NGRX Effect - Re-throw an error and catch it in a component


I have and effect that sends a request to an API Endpoint. If an error occurs, the server responses with an error message.

I want to be able to re-throw that error to upper layer to handle it there. I have tried try and catch but that seems to be not working as I would expect. Any ideas?

Store effect:

createUser$ = createEffect(() =>
  this.actions$.pipe(
    ofType(UserActions.createUser),
    mergeMap((user) =>
      this.http.post<User>('/api/users', user).pipe(
        map((newUser) => {
          return UserActions.createUserSuccess(newUser)
        }),
        catchError((err: HttpErrorResponse) => {
          UserActions.createUserFailure(err)

          // Here I am re-throwing the error
          return throwError(() => err.error)
        }),
      ),
    ),
  ),
)

Facade:

addUser(user: User) {
  this.store.dispatch(UserActions.createUser(user))
}

Usage in component:

try {
  this.userFacade.addUser(user)
} catch (error) {
  // Here I want to catch the error and display it
  this.messageService.showError(error.message)
}

Solution

  • UI is driven via store, so you need to create an action

    createUserFail
    

    pass error payload message to state and then use selector to map the error message on the Frontend.

    Make a slight modification to your effect as mentioned below.

    createUser$ = createEffect(() =>
      this.actions$.pipe(
        ofType(UserActions.createUser),
        mergeMap((user) =>
          this.http.post<User>('/api/users', user).pipe(
            map((newUser) => {
              return UserActions.createUserSuccess(newUser)
            }),
            catchError((err: HttpErrorResponse) => {          
              // Here I am re-throwing the error
              return throwError(() => err.error)
            }),
          ),
        ),
       catchError(err => {
         return UserActions.createUserFailure({ payload: err.message })
       })
      ),
    )