rxjs#throwError TypeScript Examples

The following examples show how to use rxjs#throwError. 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: 1inch.api.service.ts    From gnosis.1inch.exchange with MIT License 6 votes vote down vote up
function delayedRetry(delayMs: number, maxRetry = DEFAULT_MAX_RETRIES) {
  let retries = maxRetry;

  return (src: Observable<any>) =>
    src.pipe(
      retryWhen((errors: Observable<any>) => errors.pipe(
        delay(delayMs),
        mergeMap(error => retries-- > 0 ? of(error) : throwError(error))
      ))
    );
}
Example #2
Source File: unauthorized.interceptor.ts    From Smersh 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 && [401, 403].includes(error.status)) {
          this.router.navigateByUrl(DashboardRouter.redirectToList());
        }
        return throwError(error);
      })
    );
  }
Example #3
Source File: websocket-client.ts    From closer-sdk.js with MIT License 6 votes vote down vote up
/**
   * Cold observable
   * @param command Message
   */
  public ask(command: roomCommand.SendMessage | roomCommand.SendCustomMessage): Observable<chatEvents.Received> {
    const ref = this.uuidGenerator.next();
    const newCommand = { ...command, ref };

    return merge(
      of(newCommand).pipe(
        tap((cmd: typeof newCommand) => this.send(cmd)),
        ignoreElements(),
      ),
      this.connection$.pipe(
        filter(chatEvents.Received.isReceived),
        filter(rec => rec.ref === ref),
      ),
      this.connection$.pipe(
        filter(errorEvents.Error.isError),
        filter(rec => rec.ref === ref),
        mergeMap(err => throwError(err, undefined)),
      ),
    ).pipe(
      timeout(this.askTimeoutMs),
      take(1),
    );
  }
Example #4
Source File: liquidity-pools.service.ts    From xBull-Wallet with GNU Affero General Public License v3.0 6 votes vote down vote up
// getLatestPools(data: { horizonApi: IHorizonApi }): Observable<ILpAssetLoaded[]> {
  getPoolsByAssets(data: { assets: Asset[], horizonApi: IHorizonApi }): Observable<ILpAssetLoaded[]> {
    this.lpAssetsStore.updateUIState({ fetchingLatestPools: true });
    const serverCall = new this.stellarSdkService.SDK.Server(data.horizonApi.url)
      .liquidityPools()
      .forAssets(...data.assets)
      .limit(100)
      .order('desc')
      .call();

    return from(serverCall)
      .pipe(map(response => {
        return response.records.map((record): ILpAssetLoaded => ({
          _id: record.id,
          reserves: record.reserves,
          fee_bp: record.fee_bp,
          dataLoaded: true,
          totalShares: record.total_shares,
          totalTrustlines: record.total_trustlines,
        }));
      }))
      .pipe(withTransaction(lpAssets => {
        this.lpAssetsStore.set(lpAssets);
        this.lpAssetsStore.updateUIState({ fetchingLatestPools: false });
      }))
      .pipe(catchError(response => {
        this.lpAssetsStore.updateUIState({ fetchingLatestPools: false });
        return throwError(response);
      }));
  }
Example #5
Source File: my-trades.service.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
public depositPolygonBridgeTradeAfterCheckpoint(
    burnTransactionHash: string,
    onTransactionHash: (hash: string) => void
  ): Observable<TransactionReceipt> {
    try {
      this.walletConnectorService.checkSettings(BLOCKCHAIN_NAME.ETHEREUM);
    } catch (err) {
      return throwError(err);
    }

    return this.ethereumPolygonBridgeService
      .depositTradeAfterCheckpoint(burnTransactionHash, onTransactionHash)
      .pipe(
        catchError((err: unknown) => {
          if ((err as RubicError<ERROR_TYPE>)?.code === 4001) {
            return throwError(new UserRejectError());
          }
          return throwError(err);
        })
      );
  }
Example #6
Source File: product.service.ts    From Angular-ActionStreams with MIT License 6 votes vote down vote up
private handleError(err: any): Observable<never> {
    // in a real world app, we may send the server to some remote logging infrastructure
    // instead of just logging it to the console
    let errorMessage: string;
    if (err.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      errorMessage = `An error occurred: ${err.error.message}`;
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong,
      errorMessage = `Backend returned code ${err.status}: ${err.body.error}`;
    }
    console.error(err);
    return throwError(errorMessage);
  }
Example #7
Source File: product.service.ts    From Angular-HigherOrderMapping with MIT License 6 votes vote down vote up
private handleError(err: any) {
    // in a real world app, we may send the server to some remote logging infrastructure
    // instead of just logging it to the console
    let errorMessage: string;
    if (err.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      errorMessage = `An error occurred: ${err.error.message}`;
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong,
      errorMessage = `Backend returned code ${err.status}: ${err.body.error}`;
    }
    console.error(err);
    return throwError(errorMessage);
  }
Example #8
Source File: auth.service.ts    From ng-devui-admin with MIT License 6 votes vote down vote up
login(account: string, password: string) {
    for (let i = 0; i < USERS.length; i++) {
      if (account === USERS[i].account && password === USERS[i].password) {
        let { userName, gender, phoneNumber, email } = USERS[i];
        let userInfo: User = { userName, gender, phoneNumber, email };
        return of(userInfo);
      }
    }
    return throwError('Please make sure you have input correct account and password');
  }
Example #9
Source File: fake-backend.service.ts    From ng-conf-2020-workshop with MIT License 6 votes vote down vote up
registerHandle(newUser: StorageUser, update = false) {
        const duplicateUser = this.users.find(user => user.email === newUser.email);
        if (duplicateUser && !update) {
            return throwError({ error: { message: 'Account with email "' + newUser.email + '" already exists' } });
        }
        if (update && duplicateUser) {
            Object.assign(duplicateUser, newUser);
        } else {
            this.users.push(newUser);
        }
        this.localStorage.setItem('users', JSON.stringify(this.users));

        const body = this.getUserJWT(newUser);

        return of(new HttpResponse({ status: 200, body: this.generateToken(body) }));
    }
Example #10
Source File: AuthInterceptor.ts    From barista with Apache License 2.0 6 votes vote down vote up
private handleAuthError(err: HttpErrorResponse): Observable<any> {
    // handle your auth error or rethrow
    if (err.status === 401 || err.status === 403) {
      // navigate /delete cookies or whatever
      this.authService.logout();
      window.location.reload();
      if(!this.router.url.endsWith('/signin')){
        this.router.navigate(['/home']);
      }
      return of(err.message);
    }

    // relay error message from ImATeapotException to authservice
    if (err.status === 418) {
      throw new Error(err.error.message);
    }

    return throwError(err);
  }
Example #11
Source File: upcdatabase.service.ts    From pantry_party with Apache License 2.0 6 votes vote down vote up
private decodeResponse(doc: string) {
    switch (this.getStringFieldValue(doc, "message")) {
      case "Database entry found":
        return of({ name: this.getStringFieldValue(doc, "description") });
      case "No database entry found.":
        return throwError("Not found");
      case "Invalid credentials":
        this.receivingErrors = true;

        return throwError("Auth Errorx");
      case "":
      default:
        return throwError("Unknown Error");
    }
  }
Example #12
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 #13
Source File: manifest-collector.ts    From scion-microfrontend-platform with Eclipse Public License 2.0 6 votes vote down vote up
private async fetchAndRegisterManifest(appConfig: ApplicationConfig, monitor: ProgressMonitor): Promise<void> {
    try {
      if (!appConfig.manifestUrl) {
        Beans.get(Logger).error(`[AppConfigError] Failed to fetch manifest for application '${appConfig.symbolicName}'. Manifest URL must not be empty.`);
        return;
      }

      const fetchManifest$ = from(Beans.get(HttpClient).fetch(appConfig.manifestUrl));
      const manifestFetchTimeout = appConfig.manifestLoadTimeout ?? Beans.get(MicrofrontendPlatformConfig).manifestLoadTimeout;
      const onManifestFetchTimeout = (): Observable<never> => throwError(() => `Timeout of ${manifestFetchTimeout}ms elapsed.`);
      const manifestFetchResponse = await firstValueFrom(fetchManifest$.pipe(manifestFetchTimeout ? timeout({first: manifestFetchTimeout, with: onManifestFetchTimeout}) : identity));

      if (!manifestFetchResponse.ok) {
        Beans.get(Logger).error(`[ManifestFetchError] Failed to fetch manifest for application '${appConfig.symbolicName}'. Maybe the application is currently unavailable. [httpStatusCode=${manifestFetchResponse.status}, httpStatusText=${manifestFetchResponse.statusText}]`, appConfig, manifestFetchResponse.status);
        return;
      }

      const manifest: Manifest = await manifestFetchResponse.json();

      // Let the host manifest be intercepted before registering it in the platform, for example by libraries integrating the SCION Microfrontend Platform, e.g., to allow the programmatic registration of capabilities or intentions.
      if (appConfig.symbolicName === Beans.get<string>(APP_IDENTITY)) {
        Beans.all(HostManifestInterceptor).forEach(interceptor => interceptor.intercept(manifest));
      }

      Beans.get(ApplicationRegistry).registerApplication(appConfig, manifest);
      Beans.get(Logger).info(`Registered application '${appConfig.symbolicName}' in the SCION Microfrontend Platform.`);
    }
    catch (error) {
      // The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500.
      // It will only reject on network failure or if anything prevented the request from completing.
      // See https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Checking_that_the_fetch_was_successful
      Beans.get(Logger).error(`[ManifestFetchError] Failed to fetch manifest for application '${appConfig.symbolicName}'. Maybe the application is currently unavailable.`, error);
    }
    finally {
      monitor.done();
    }
  }
Example #14
Source File: emote.structure.ts    From App with MIT License 6 votes vote down vote up
/**
	 * Delete this emote
	 */
	delete(reason?: string): Observable<void> {
		if (!this.id) return throwError(Error('Cannot delete unknown emote'));

		return this.getRestService().v2.DeleteEmote(this.id, reason).pipe(
			mapTo(undefined)
		);
	}
Example #15
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 #16
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 #17
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 #18
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 #19
Source File: auth.service.ts    From router with MIT License 6 votes vote down vote up
login({ username, password }: Credentials): Observable<User> {
    /**
     * Simulate a failed login to display the error
     * message for the login form.
     */
    if (username !== 'test' && username !== 'ngrx') {
      return throwError('Invalid username or password');
    }

    return of({ name: 'User' });
  }
Example #20
Source File: courses.store.ts    From reactive-angular-course with MIT License 6 votes vote down vote up
private loadAllCourses() {

        const loadCourses$ = this.http.get<Course[]>('/api/courses')
            .pipe(
                map(response => response["payload"]),
                catchError(err => {
                    const message = "Could not load courses";
                    this.messages.showErrors(message);
                    console.log(message, err);
                    return throwError(err);
                }),
                tap(courses => this.subject.next(courses))
            );

        this.loading.showLoaderUntilCompleted(loadCourses$)
            .subscribe();

    }
Example #21
Source File: auth.interceptor.ts    From auth0-angular with MIT License 6 votes vote down vote up
/**
   * Duplicate of AuthService.getAccessTokenSilently, but with a slightly different error handling.
   * Only used internally in the interceptor.
   * @param options The options for configuring the token fetch.
   */
  private getAccessTokenSilently(
    options?: GetTokenSilentlyOptions
  ): Observable<string> {
    return of(this.auth0Client).pipe(
      concatMap((client) => client.getTokenSilently(options)),
      tap((token) => this.authState.setAccessToken(token)),
      catchError((error) => {
        this.authState.refresh();
        return throwError(error);
      })
    );
  }
Example #22
Source File: auth.interceptor.ts    From budget-angular with GNU General Public License v3.0 6 votes vote down vote up
intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    if (config.auth === "token" && this.jwt && this.jwt.getToken()) {
      request = this.addToken(request, this.jwt.getToken());
    }

    return next.handle(request).pipe(
      catchError((error) => {
        if (error.status === 401) {
          this.authService.doLogoutAndRedirectToLogin();
        }
        return throwError(error);
      })
    );
  }
Example #23
Source File: api.service.ts    From blockcore-hub with MIT License 6 votes vote down vote up
/** Use this to handle error in the initial startup (wallet/files) of Blockcore Hub. */
    handleInitialError(error: HttpErrorResponse | any) {
        // Only show snackbar errors when we have connected. Initially we will receive some errors due to aggresive
        // attempts at connecting to the node.
        if (this.appState.connected) {
            this.handleException(error);
        }

        return throwError(error);
    }
Example #24
Source File: file-upload.service.ts    From careydevelopmentcrm with MIT License 6 votes vote down vote up
private handleError(error: HttpErrorResponse) {
        if (error.error instanceof ErrorEvent) {
            // A client-side or network error occurred. Handle it accordingly.
            console.error('An error occurred:', error.error.message);
        } else {
            // The backend returned an unsuccessful response code.
            console.error(
                `Backend returned code ${error.status}, ` +
                `body was: ${error.error}`);

            if (error.status == 403) {
                throw new Error("You are not permitted to make changes on this account");
            }

            throw new Error("Unexpected error - please try again later");
        }

        // return an observable with a user-facing error message
        return throwError("Unexpected error - please try again later");
    }
Example #25
Source File: api-connector.ts    From attack-workbench-frontend with Apache License 2.0 6 votes vote down vote up
/**
     * Log the error and then raise it to the next level
     * @param {boolean} showSnack if true, show the error snackbar
     */
    protected handleError_raise<T>(showSnack: boolean = true) {
        return (error: any): Observable<T> => {
            logger.error(error);
            if (showSnack) this.errorSnack(error);
            return throwError(error);
        }
    }
Example #26
Source File: error.interceptor.ts    From angular-10-basic-authentication-example with MIT License 6 votes vote down vote up
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(catchError(err => {
            if (err.status === 401) {
                // auto logout if 401 response returned from api
                this.authenticationService.logout();
            }

            const error = err.error.message || err.statusText;
            return throwError(error);
        }))
    }
Example #27
Source File: error.interceptor.ts    From angular-10-facebook-login-example with MIT License 6 votes vote down vote up
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(catchError(err => {
            if ([401, 403].includes(err.status)) {
                // auto logout if 401 or 403 response returned from api
                this.accountService.logout();
            }

            const error = err.error?.message || err.statusText;
            console.error(err);
            return throwError(error);
        }))
    }
Example #28
Source File: error.interceptor.ts    From angular-10-jwt-authentication-example with MIT License 6 votes vote down vote up
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(catchError(err => {
            if (err.status === 401) {
                // auto logout if 401 response returned from api
                this.authenticationService.logout();
                location.reload(true);
            }

            const error = err.error.message || err.statusText;
            return throwError(error);
        }))
    }
Example #29
Source File: error.interceptor.ts    From angular-10-jwt-refresh-tokens with MIT License 6 votes vote down vote up
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(catchError(err => {
            if ([401, 403].includes(err.status) && this.authenticationService.userValue) {
                // auto logout if 401 or 403 response returned from api
                this.authenticationService.logout();
            }

            const error = (err && err.error && err.error.message) || err.statusText;
            console.error(err);
            return throwError(error);
        }))
    }