rxjs/operators#catchError TypeScript Examples

The following examples show how to use rxjs/operators#catchError. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: onboarding.page.ts    From mylog14 with GNU General Public License v3.0 6 votes vote down vote up
onSubmit() {
    this.confirmButtonEnabled = false;
    const loading$ = this.showRegisteringUserLoading();
    const signup$ = this.privateCouponService.signup(this.onboardingForm.controls.email.value)
      .pipe(
        catchError((err: HttpErrorResponse) => {
          if (err.error.reason === 'USED_EMAIL') {
            console.log('The API returns USED_EMAIL error.');
            return of(null);
          }
          console.error(err);
          this.confirmButtonEnabled = true;
          this.presentToast(err.error.reason || err.statusText);
          throw (err);
        }),
        map((res: SignupResponse) => ({
          email: this.onboardingForm.controls.email.value,
          newUser: false,
          recordPreset: RecordPreset.COMMON_COLD,
          userId: (res) ? res.response.user_id : null,
        })),
        switchMap(userDataPatch => this.dataStore.updateUserData(userDataPatch)),
      );

    loading$
      .pipe(
        tap(loadingElement => this.loadingElement = loadingElement),
        switchMap(loadingElement => signup$.pipe(map(() => loadingElement))),
        switchMap(loadingElement => loadingElement.dismiss()),
      )
      .subscribe(() => {
        this.router.navigate(['/']);
      }, () => {
        this.loadingElement.dismiss();
      });
  }
Example #2
Source File: build-accept-offer.component.ts    From bitcoin-s-ts with MIT License 6 votes vote down vote up
handleAcceptOffer(hex: string) {
    console.debug('handleAcceptOffer()', hex)
    if (hex) {
      if (!this.validateHex(hex)) return

      this.messageService.sendMessage(getMessageBody(CoreMessageType.decodeoffer, [hex]), false)
      .pipe(catchError(error => of({ result: null }))).subscribe(r => {
        console.debug('decodeoffer', r)

        if (r.result) {
          this.onAcceptOffer(<OfferWithHex>{ offer: r.result, hex })
        } else {
          const dialog = this.dialog.open(ErrorDialogComponent, {
            data: {
              title: 'dialog.error',
              content: 'buildAcceptOffer.invalidOfferHex',
            }
          })
        }
      })
    }
  }
Example #3
Source File: account.component.ts    From budget-angular with GNU General Public License v3.0 6 votes vote down vote up
private getCreateUserCallback$(): (user: User) => Observable<void> {
    return (user: User) =>
      this.accountService.createUser(user).pipe(
        switchMap(() => this.loadUsers$()),
        tap(() => this.showResultSnackbar("Success")),
        catchError((errorResponse) => {
          this.showResultSnackbar(errorResponse.error?.msg ?? "Unknown error");
          return of(errorResponse);
        })
      );
  }
Example #4
Source File: auth.service.ts    From auth0-angular with MIT License 6 votes vote down vote up
constructor(
    @Inject(Auth0ClientService) private auth0Client: Auth0Client,
    private configFactory: AuthClientConfig,
    private navigator: AbstractNavigator,
    private authState: AuthState
  ) {
    const checkSessionOrCallback$ = (isCallback: boolean) =>
      iif(
        () => isCallback,
        this.handleRedirectCallback(),
        defer(() => this.auth0Client.checkSession())
      );

    this.shouldHandleCallback()
      .pipe(
        switchMap((isCallback) =>
          checkSessionOrCallback$(isCallback).pipe(
            catchError((error) => {
              const config = this.configFactory.get();
              this.authState.setError(error);
              this.navigator.navigateByUrl(config.errorPath || '/');
              return of(undefined);
            })
          )
        ),
        tap(() => {
          this.authState.setIsLoading(false);
        }),
        takeUntil(this.ngUnsubscribe$)
      )
      .subscribe();
  }
Example #5
Source File: courses.store.ts    From reactive-angular-course with MIT License 6 votes vote down vote up
saveCourse(courseId:string, changes: Partial<Course>): Observable<any> {

        const courses = this.subject.getValue();

        const index = courses.findIndex(course => course.id == courseId);

        const newCourse: Course = {
          ...courses[index],
          ...changes
        };

        const newCourses: Course[] = courses.slice(0);

        newCourses[index] = newCourse;

        this.subject.next(newCourses);

        return this.http.put(`/api/courses/${courseId}`, changes)
            .pipe(
                catchError(err => {
                    const message = "Could not save course";
                    console.log(message, err);
                    this.messages.showErrors(message);
                    return throwError(err);
                }),
                shareReplay()
            );
    }
Example #6
Source File: collection.effects.ts    From router with MIT License 6 votes vote down vote up
removeBookFromCollection$ = createEffect(() =>
    this.actions$.pipe(
      ofType(SelectedBookPageActions.removeBook),
      mergeMap(({ book }) =>
        this.storageService.removeFromCollection([book.id]).pipe(
          map(() => CollectionApiActions.removeBookSuccess({ book })),
          catchError(() => of(CollectionApiActions.removeBookFailure({ book })))
        )
      )
    )
  );
Example #7
Source File: http-error.interceptor.ts    From angular-padroes-e-boas-praticas with MIT License 6 votes vote down vote up
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
      catchError((httpError: HttpErrorResponse) => {
        console.error('Error from interceptor', httpError);
        this.notification.error(httpError.error || 'An unexpected error occurred!');
        return throwError(httpError);
      })
    ) as Observable<HttpEvent<any>>;
  }
Example #8
Source File: auth.interceptor.ts    From ngx-admin-dotnet-starter with MIT License 6 votes vote down vote up
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req)
      .pipe(catchError((error: HttpErrorResponse) => {
        if (error.status === 401) {
          this.router.navigate(['auth/login']);
        }
        // TODO: handle 403 error ?
        return throwError(error);
      }));
  }
Example #9
Source File: http-error.interceptor.ts    From ReCapProject-Frontend with MIT License 6 votes vote down vote up
intercept(
    request: HttpRequest<unknown>,
    next: HttpHandler
  ): Observable<HttpEvent<unknown>> {
    return next.handle(request).pipe(
      catchError((responseError: HttpErrorResponse) => {
        if (responseError.error.Errors && responseError.error.Errors.length > 0)
          responseError.error.Errors.forEach((error: any) =>
            this.toastrService.error(error.ErrorMessage)
          );
        else if (responseError.error.message)
          this.toastrService.error(responseError.error.message);
        else this.toastrService.error('An problem has occurred.');

        console.log(
          `! ~ file: http-error.interceptor.ts ~ line 24 ~ error`,
          responseError
        ); // Test

        return throwError(responseError);
      })
    );
  }
Example #10
Source File: link.service.ts    From WowUp with GNU General Public License v3.0 6 votes vote down vote up
private showLinkNavigationDialog(href: string, domains: string[]): Observable<any> {
    const dialogRef = this._dialog.open(ExternalUrlConfirmationDialogComponent, {
      data: {
        title: this._translateService.instant("APP.LINK_NAVIGATION.TITLE"),
        message: this._translateService.instant("APP.LINK_NAVIGATION.MESSAGE", { url: href }),
        url: href,
        domains,
      },
    });

    return dialogRef.afterClosed().pipe(
      first(),
      switchMap((result: DialogResult) => {
        if (!result.success) {
          return of(undefined);
        }

        if (result.trustDomain !== "") {
          return from(this._wowUpService.trustDomain(result.trustDomain)).pipe(
            switchMap(() => from(this.openExternalLink(href)))
          );
        } else {
          return from(this.openExternalLink(href));
        }
      }),
      catchError((e) => {
        console.error("failed to open external link", e);
        return of(undefined);
      })
    );
  }
Example #11
Source File: base-user-apollo.service.ts    From svvs with MIT License 6 votes vote down vote up
// eslint-disable-next-line @typescript-eslint/no-unused-vars
  loadUser(queryParams: Record<string, unknown> = {}): TApolloResponse<IUser> {
    return this.apollo
      .query<{ user: IUser}>( {query: UserQieries.usersRequest.query} )
      .pipe(
        map(result => extractApolloResponse(result, UserQieries.usersRequest.keys)),
        catchError((error: ApolloError) => throwError(error))
      )
  }
Example #12
Source File: store.component.ts    From App with MIT License 6 votes vote down vote up
ngOnInit(): void {
		this.appService.subscription.pipe(
			filter(sub => sub !== null),
			switchMap(sub => this.restService.Discord.Widget().pipe(
				RestService.onlyResponse(),
				tap(d => this.discordInvite = d.body?.instant_invite ?? ''),
				catchError(() => of(sub)),
				mapTo(sub)
			)),

			// Fetch gifter?
			switchMap(sub => iif(() => !!sub?.gifter_id,
				this.restService.v2.GetUser(sub?.gifter_id as string).pipe(
					map(res => this.dataService.add('user', res.user)[0]),
					tap(u => this.gifter = u),
					mapTo(sub)
				),
				of(sub)
			))
		).subscribe({
			next: sub => {
				this.subscription.next(sub);
			}
		});

		this.appService.egvaultOK.pipe(filter(x => x !== null)).pipe(
			tap(ok => {
				this.available.next(ok);
				if (!ok) {
					this.clientService.openSnackBar('Subscription service is currenty unavailable, try again in a minute', 'OK', { duration: 3000, verticalPosition: 'top' });
					this.router.navigate(['/']);
				}
			})
		).subscribe({
			complete: () => this.cdr.markForCheck()
		});
	}
Example #13
Source File: message-broker.ts    From scion-microfrontend-platform with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Catches and logs errors, and resubscribes to the source observable.
 *
 * @ignore
 */
function catchErrorAndRetry<T>(): MonoTypeOperatorFunction<T> {
  return catchError((error, caught) => {
    Beans.get(Logger).error('[UnexpectedError] An unexpected error occurred.', error);
    return caught;
  });
}
Example #14
Source File: exception.interceptor.ts    From domain-driven-hexagon with MIT License 6 votes vote down vote up
intercept(
    _context: ExecutionContext,
    next: CallHandler,
  ): Observable<ExceptionBase> {
    return next.handle().pipe(
      catchError(err => {
        /**
         * Custom exceptions are converted to nest.js exceptions.
         * This way we are not tied to a framework or HTTP protocol.
         */
        if (err instanceof NotFoundException) {
          throw new NestNotFoundException(err.message);
        }
        if (err instanceof ConflictException) {
          throw new NestConflictException(err.message);
        }
        return throwError(err);
      }),
    );
  }
Example #15
Source File: upcitemdb.service.ts    From pantry_party with Apache License 2.0 6 votes vote down vote up
lookForBarcode(barcode: string): Observable<ExternalProduct> {
    if (!this.enabled) {
      return EMPTY;
    }

    return this.http.get<ItemLookupResponse>(
      "https://api.upcitemdb.com/prod/trial/lookup",
      {
        params: {
          upc: convertToUpcAIfRequired(barcode)
        }
      }
    ) .pipe(
      catchError(() => EMPTY),
      switchMap(r => {
      if (r.items.length === 0) {
        return EMPTY;
      } else {
        let name = r.items[0].title;

        if (r.items[0].brand) {
          name += ` (${r.items[0].brand})`;
        }

        return of({ name });
      }
    })
    );
  }
Example #16
Source File: app.effects.ts    From Angular-Cookbook with MIT License 6 votes vote down vote up
getUsers$ = createEffect(() =>
    this.actions$.pipe(
      ofType(APP_ACTIONS.GET_USERS),
      mergeMap(() =>
        this.userService.getUsers().pipe(
          map((users) => {
            return getUsersSuccess({
              users,
            });
          }),
          catchError((error) =>
            of(
              getUsersFailure({
                error,
              })
            )
          )
        )
      )
    )
  );
Example #17
Source File: assets.service.ts    From nica-os with MIT License 6 votes vote down vote up
private loadAsset(assetKey: string) {
    return this.http.get(`assets/${this.assetsToLoad[assetKey].path}`, {responseType: 'text'})
      .pipe(
        switchMap(res => {
          this.store$.dispatch(setLoadingMessage({message: `<i><pre>[200]</pre> LOADED </i>: ${assetKey}`}));
          return of(res);
        }),
        catchError(err => {
          this.store$.dispatch(setLoadingMessage(
            {message: `<small>ERROR</small>: ${assetKey} - <small>${err.status} - ${err.statusText}</small>`}));
          return of(null);
        })
      );
  }
Example #18
Source File: upload.service.ts    From mylog14 with GNU General Public License v3.0 6 votes vote down vote up
private postArchive(blob: Blob) {
    const hostUrl = {
      LOCAL: 'http://127.0.0.1:8000',
      DEV: 'https://logboard-dev.numbersprotocol.io',
      PROD: 'https://mylog14.numbersprotocol.io',
    };
    const endpoint = '/api/v1/archives/';
    const formData = new FormData();
    formData.append('file', blob, 'mylog.zip');
    const hostType = 'PROD';
    const url = hostUrl[hostType] + endpoint;
    return this.http.post(url, formData)
      .pipe(
        map((res: string) => res.replace(hostUrl.PROD, hostUrl[hostType])),
        tap(logboardUrl => this.generatedUrl.next(logboardUrl)),
        catchError(err => this.httpErrorHandler(err)),
      );
  }
Example #19
Source File: epic.ts    From Shopping-Cart with MIT License 6 votes vote down vote up
fetchCouponListEpic: Epic = (
  action$: ActionsObservable<Actions>,
  _,
  { productService }: Service,
) =>
  action$.pipe(
    filter(isActionOf(fetchCouponListAsync.request)),
    switchMap(() =>
      of(productService.getCoupons()).pipe(
        switchMap(payload => {
          return of(fetchCouponListAsync.success({ data: payload }));
        }),
      ),
    ),
    catchError(err => {
      return of(fetchCouponListAsync.failure(err));
    }),
  )
Example #20
Source File: ajax-flow.ts    From RcloneNg with MIT License 6 votes vote down vote up
protected requestCache(pre: CombErr<Tin>): Observable<CombErr<Tout>> {
		return ajax(this.requestAjax(pre)).pipe(
			map(x => [{ ajaxRsp: x }, []] as CombErr<AjaxFlowInteralNode>),
			catchError(
				(err): Observable<CombErr<AjaxFlowInteralNode>> =>
					of([{}, [err]] as CombErr<AjaxFlowInteralNode>)
			),
			map(x => this.reconstructAjaxResult(x))
		);
	}
Example #21
Source File: index.ts    From dbm with Apache License 2.0 6 votes vote down vote up
/* ----------------------------------------------------------------------------
 * Functions
 * ------------------------------------------------------------------------- */

/**
 * Resolve a pattern
 *
 * @param pattern - Pattern
 * @param options - Options
 *
 * @returns File observable
 */
export function resolve(
  pattern: string, options?: ResolveOptions
): Observable<string> {
  return from(glob(pattern, options))
    .pipe(
      catchError(() => EMPTY),
      switchMap(files => from(files)),
      options?.watch
        ? mergeWith(watch(pattern, options))
        : identity
    )
}
Example #22
Source File: product.service.ts    From Angular-HigherOrderMapping with MIT License 6 votes vote down vote up
// Try mergeMap, switchMap, concatMap
  product$ = this.productSelectedAction$
    .pipe(
      filter(id => !!id),
      switchMap(selectedProductId =>
        this.http.get<Product>(`${this.productsUrl}/${selectedProductId}`)
          .pipe(
            tap(response => console.log(JSON.stringify(response))),
            map(p => ({ ...p, profit: p.price - p.cost }) as Product),
            catchError(this.handleError)
          )
      ));
Example #23
Source File: staking.service.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Calculates what amount of BRBC user will get if withdraw provided amount of xBRBC.
   * @param amount Amount of tokens that user wants to withdraw.
   * @return Observable<BigNumber>
   */
  public calculateLeaveReward(amount: BigNumber): Observable<BigNumber> {
    if (amount.isZero()) {
      return of(new BigNumber(0));
    }
    return from(
      this.web3PublicService[BLOCKCHAIN_NAME.BINANCE_SMART_CHAIN].callContractMethod(
        this.stakingContractAddress,
        this.stakingContractAbi,
        'canReceive',
        {
          methodArguments: [amount.toFixed(0)]
        }
      )
    ).pipe(
      catchError((error: unknown) => {
        this.errorService.catchAnyError(error as RubicError<ERROR_TYPE.RAW_MESSAGE>);
        return EMPTY;
      }),
      map(res => Web3Pure.fromWei(res))
    );
  }