Dmitry
Dmitry

Reputation: 127

Handle ngrx effect catchError properly

Hello I have an Effect and want to handle error properly. I want to call an additional action with content of my server side error. How could I do this?

@Injectable()
export class AuthEffects {
    @Effect()
    registerUser$ = this.actions$.pipe(
      ofType(AuthActions.Action.CREATE_USER),
      switchMap(({user}) =>
        this.customersService.createNewUser(user).pipe(
          switchMap(() => [
            new ModalActions.SetModalType(null)
            ]
          ),
            catchError((err) => {
              if (foo) {
              new ModalActions.SetModalErrors(err.error); // <---- make an Action here
              } else {
              }
              return throwError(err);
            })

            )
        )
    );

Upvotes: 1

Views: 2034

Answers (2)

quetzalcoatl
quetzalcoatl

Reputation: 33506

Just like you return the result of throwError() from catchError, you should be able to simply return array of actions in the other case

      catchError((err) => {
        if (foo) {
          // whatever you return here, should be an Observable-ish thing
          // an Observable of(), an array, etc
          return [
            new ModalActions.SetModalErrors(err.error),
          ];
        } else {
          return throwError(err);
        }
      })

Upvotes: 0

Dmitry
Dmitry

Reputation: 127

Unfortunately nobody answered, but anyway this works:

catchError((err) => {
  if (err.error.email) {
    return of(new ModalActions.SetModalErrors(err.error));
  } else {
  this.notificationService.notify(Object.values(err.error)[0] as string);
  return throwError(err);
  }
}

Upvotes: 1

Related Questions