@angular/common/http#HttpErrorResponse TypeScript Examples

The following examples show how to use @angular/common/http#HttpErrorResponse. 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: 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 #2
Source File: common-oneinch.service.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
private specifyError(err: unknown, blockchain: EthLikeBlockchainName): never {
    if (err instanceof HttpErrorResponse) {
      if (err.error.message?.includes('cannot estimate')) {
        const nativeToken = networks.find(el => el.name === blockchain).nativeCoin.symbol;
        const message = `1inch sets increased costs on gas fee. For transaction enter less ${nativeToken} amount or top up your ${nativeToken} balance.`;
        throw new CustomError(message);
      }
      if (err.error.message?.includes('insufficient funds for transfer')) {
        const nativeToken = networks.find(el => el.name === blockchain).nativeCoin.symbol;
        throw new InsufficientFundsOneinchError(nativeToken);
      }
      if (err.error.description?.includes('cannot estimate')) {
        throw new TokenWithFeeError();
      }
      throw new CustomError(err.error.message);
    }
    if (err instanceof Error) {
      throw new CustomError(err.message);
    }
    throw new CustomError(err?.toString());
  }
Example #3
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 #4
Source File: home.component.ts    From msfs-community-downloader with GNU Affero General Public License v3.0 6 votes vote down vote up
ngOnInit(): void {
        this.packages = this.domainService.getPackages();

        const removedPackageIds = this.settingsService.getSettings().removedPackageIds;

        const removedPackages = this.packages.filter(x => removedPackageIds.includes(x.id));
        for (const rp of removedPackages) {
            rp.isSelected = false;
        }
        this.packages = this.packages.filter(x => !removedPackageIds.includes(x.id));

        if (this.packages.length > 0) {
            let selected = this.packages.find(x => x.isSelected);

            if (!selected) {
                selected = this.packages[0];
                selected.isSelected = true;
            }

            this.selectedPackage = selected;
            this.domainService.analysePackages(this.packages)
                .catch((err: HttpErrorResponse) => {
                    this.analyseHttpError(err);
                });
        }
    }
Example #5
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 #6
Source File: grocy-api.component.ts    From pantry_party with Apache License 2.0 6 votes vote down vote up
ngOnInit(): void {
    merge(
      this.form.valueChanges,
      this.forceCheck
    ).pipe(
      tap(() => this.updateValidationStatus()),
      takeUntil(this.ngUnsubscribe),
      debounceTime(250),
      filter(() =>  this.form.valid),
      tap(() => this.working = true),
      switchMap(_ => this.grocyService.getSystemInfo(
        this.formControl("url").value,
        this.formControl("apiKey").value
      ).pipe(
      map(r => ({result: "success" as "success", resp: r})),
      catchError((e: HttpErrorResponse) => of({result: "error" as "error", err: e}))
      )),
      tap(() => this.working = false)
    ).subscribe(r =>  this.renderReturn(r));

    if (this.form.valid) {
      this.forceCheck.next(true);
    }
  }
Example #7
Source File: emote.component.ts    From App with MIT License 6 votes vote down vote up
/**
	 * Method called when the client user interacts with a button
	 */
	onInteract(interaction: ContextMenuComponent.InteractButton): void {
		if (typeof interaction.click === 'function' && !!this.emote) {
			interaction.click(this.emote).pipe(
				switchMap(() => iif(() => interaction.label === 'add to channel' || interaction.label === 'remove from channel',
					this.readChannels().pipe(mapTo(undefined)),
					of(undefined)
				))
			).subscribe({
				complete: () => this.interactError.next(''),
				error: (err: HttpErrorResponse) => this.interactError.next(this.restService.formatError(err))
			});
		}
	}
Example #8
Source File: github-addon-provider.ts    From WowUp with GNU General Public License v3.0 6 votes vote down vote up
private handleRateLimitError(response: HttpErrorResponse) {
    if (response.status === 403) {
      const rateLimitMax = this.getIntHeader(response.headers, HEADER_RATE_LIMIT_MAX);
      const rateLimitUsed = this.getIntHeader(response.headers, HEADER_RATE_LIMIT_USED);
      const rateLimitRemaining = this.getIntHeader(response.headers, HEADER_RATE_LIMIT_REMAINING);
      const rateLimitReset = this.getIntHeader(response.headers, HEADER_RATE_LIMIT_RESET);

      if (rateLimitRemaining === 0) {
        throw new GitHubLimitError(rateLimitMax, rateLimitUsed, rateLimitRemaining, rateLimitReset);
      }
    }
  }
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: 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 #11
Source File: login.component.ts    From alura_angular_rxjs_1 with MIT License 6 votes vote down vote up
private login(user: UserLogin): void {
    this.isLoading = true;

    this.subs.add(
      this.authService.login(user).subscribe(
        () => {
          this.isLoading = false;
          const redirect = this.authService.redirectUrl
            ? this.authService.redirectUrl
            : '/home';
          this.route.navigate([redirect]);
        },
        (error: HttpErrorResponse) => {
          this.isLoading = false;
          this.messageService.showMessageError('Senha inválida');
          this.route.navigate(['/login']);
        }
      )
    );
  }
Example #12
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 #13
Source File: error.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>> {
    return next.handle(request).pipe(
      catchError((error: HttpErrorResponse) => {
        if (!this.isErrorMessageSuppressed(error)) {
          this.showErrorMessage(error);
        }
        return throwError(error);
      })
    );
  }
Example #14
Source File: error-interceptor.ts    From bitcoin-s-ts with MIT License 6 votes vote down vote up
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(tap((event: HttpEvent<any>) => {
      if (event instanceof HttpResponse) {
        // do stuff with response if you want
      }
    }, (err: any) => {
      if (err instanceof HttpErrorResponse) {
        if (err.status === 401) {
          // redirect to the login route or show a modal?
          console.error('401 error on HTTP call, doLogout()')
          this.authService.doLogout()
        }
      }
    }));
  }
Example #15
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 #16
Source File: edit-account.component.ts    From careydevelopmentcrm with MIT License 6 votes vote down vote up
private handleError(err: Error) {
    console.log(err);
    this.loading = false;

    let alertMessage: string = 'Something went wrong, please call support';

    if (err instanceof HttpErrorResponse) {
      if (err.status) {
        if (err.status == 404) {
          alertMessage = 'Account with that ID does not exist';
        }
      }
    }

    this.alertService.error(alertMessage);
  }
Example #17
Source File: packet.service.ts    From Elastos.Essentials.App with MIT License 6 votes vote down vote up
public async createGrabCaptchaVerification(packet: Packet, previousGrabResponse: GrabResponse, captchaString: string, walletAddress: string, userDID?: string): Promise<GrabResponse> {
    Logger.log('redpackets', 'Sending captcha verification');
    try {
      let grabRequest: GrabRequest = {
        token: previousGrabResponse.token,
        captchaResponse: captchaString,
        walletAddress,
        userDID
      };
      let grabResponse = await this.http.post<GrabResponse>(`${environment.RedPackets.serviceUrl}/packets/${packet.hash}/grab`, grabRequest).toPromise();
      Logger.log('redpackets', 'Grab packet with captcha response', grabResponse);

      // Save the "grabbed" (won or lost) status so we don't try to fetch again later
      if (grabResponse.status === GrabStatus.GRABBED ||
        grabResponse.status === GrabStatus.MISSED ||
        grabResponse.status === GrabStatus.DEPLETED) {
        await this.saveGrabbedPacket(packet, grabResponse.status, grabResponse.earnedAmount);
      }

      return grabResponse;
    }
    catch (err) {
      if (err instanceof HttpErrorResponse) {
        if (err.status == 429) { // Too many requests - IP rate limitation
          return {
            status: GrabStatus.TOO_MANY_REQUEST
          };
        }
      }

      // All other cases
      Logger.error("redpackets", "Grab packet with captcha request failure", err);
      return null;
    }
  }
Example #18
Source File: server-side-validation.ts    From dating-client with MIT License 6 votes vote down vote up
export function handleServerSideValidation(error: HttpErrorResponse,  form: FormGroup): undefined | string {
  // if the error isn't with status 422 (Unprocessable Entity) don't do anything
  if (error.status !== 422) {
    return undefined;
  }

  const unhandledErrors: any[] = [];
  const validationError = error.error?.errors;

  Object.keys(validationError || {}).forEach(element => {
    const formControl = form.get(element);

    if (formControl) {
      formControl.setErrors({ serverSideError: validationError[element].join('') });
    } else {
      // Field is not defined in form but there is a validation error for it, set it globally
      unhandledErrors.push(validationError[element].join(''));
    }
  });

  if (unhandledErrors.length) {
    return unhandledErrors.join();
  }

  return undefined;
}
Example #19
Source File: api.service.ts    From EXOS-Core with MIT License 6 votes vote down vote up
/** Use this to handle error in the initial startup (wallet/files) of EXOS Core. */
    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 #20
Source File: http-error.interceptor.ts    From assetMG with Apache License 2.0 6 votes vote down vote up
intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
      catchError((error: HttpErrorResponse) => {
        if (error.error instanceof ErrorEvent) {
          // client-side error
          let errorMessage = `Client Side Error: ${error.error.message}`;
          return throwError(errorMessage);
        }
        if (error.status === 403) {
          this.openErrorDialog(error.error);
        }
        // server-side error
        return throwError(error);
      })
    );
  }
Example #21
Source File: http-interceptor.service.ts    From ng-ant-admin with MIT License 6 votes vote down vote up
private handleError(error: HttpErrorResponse): Observable<never> {
    const status = error.status;
    let errMsg = '';
    if (status === 0) {
      errMsg = '网络出现未知的错误,请检查您的网络。';
    }
    if (status >= 300 && status < 400) {
      errMsg = '请求被服务器重定向,状态码为' + status;
    }
    if (status >= 400 && status < 500) {
      errMsg = '客户端出错,可能是发送的数据有误,状态码为' + status;
    }
    if (status >= 500) {
      errMsg = '服务器发生错误,状态码为' + status;
    }
    return throwError({
      code: status,
      message: errMsg
    });
  }
Example #22
Source File: ns-http-backend.ts    From nativescript-http with MIT License 6 votes vote down vote up
function createErrorResponse(
    url: string,
    body: any,
    status: number): HttpErrorResponse {
    return new HttpErrorResponse({
        url,
        error: body,
        status,
        statusText: "ERROR"
    });
}
Example #23
Source File: http-error.interceptor.ts    From muino-time-management with GNU General Public License v3.0 6 votes vote down vote up
intercept(request : HttpRequest < any >, next : HttpHandler) : Observable < HttpEvent < any >> {

    return next
      .handle(request)
      .do 
        ((event : HttpEvent < any >) => {}, (err : any) => {
          if (err instanceof HttpErrorResponse) {
            let text = (err.error && err.error.message) ? err.error.message : err.statusText;
            console.log('open error dialog', text);

            (<any>window).globalEvents.emit('open error dialog', text);
          }
        });

      }
Example #24
Source File: token-verification.interceptor.ts    From litefy 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.Sair();
        }
        return throwError(error);
      }));

  }
Example #25
Source File: ignore-not-found.spec.ts    From ngx-operators with MIT License 6 votes vote down vote up
describe("ignoreNotFound", () => {
  it("should complete upon 404 status", done => {
    throwError(new HttpErrorResponse({ status: 404 }))
      .pipe(ignoreNotFound())
      .subscribe(fail, fail, done);
  });
  it("should rethrow all other errors", done => {
    throwError(new HttpErrorResponse({ status: 500 }))
      .pipe(ignoreNotFound())
      .subscribe(fail, err => {
        expect(err.status).toEqual(500);
        done();
      });
  });
  it("should pass on successful results", done => {
    const response = new HttpResponse({ status: 200, body: "success" });
    of(response)
      .pipe(ignoreNotFound())
      .subscribe(value => {
        expect(value?.body).toEqual("success");
        done();
      }, fail);
  });
});
Example #26
Source File: details.page.ts    From capture-lite with GNU General Public License v3.0 6 votes vote down vote up
private async mintNft() {
    const result = await this.confirmAlert.present({
      message: this.translocoService.translate('message.mintNftAlert'),
    });
    if (result) {
      const action$ = this.activeDetailedCapture$.pipe(
        first(),
        switchTap(activeDetailedCapture =>
          defer(() => {
            if (activeDetailedCapture.id) {
              return this.diaBackendAssetRepository.mintNft$(
                activeDetailedCapture.id
              );
            }
            return VOID$;
          })
        ),
        catchError((err: unknown) => {
          if (err instanceof HttpErrorResponse) {
            const errorType = err.error.error?.type;
            if (errorType === 'asset_is_being_minted')
              return this.errorService.toastError$(
                this.translocoService.translate(`error.diaBackend.${errorType}`)
              );
          }
          return this.errorService.toastError$(err);
        })
      );
      this.blockingActionService
        .run$(action$)
        .pipe(untilDestroyed(this))
        .subscribe();
    }
  }
Example #27
Source File: auth.interceptor.ts    From onchat-web with Apache License 2.0 6 votes vote down vote up
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    const { access, refresh } = this.tokenService.folder;

    if (access) {
      request = request.clone({
        headers: request.headers.set('Authorization', access)
      });
    }

    return next.handle(request).pipe(
      catchError((error: HttpErrorResponse) => {
        if (error.status === 401) { // 401 Unauthorized
          if (this.refresher) {
            return this.waitRefresh(request, next);
          }

          if (refresh) {
            this.refreshToken(refresh);
            return this.waitRefresh(request, next);
          }

          this.app.logout();
        }

        return throwError(() => error);
      })
    );
  }
Example #28
Source File: app-error-handler.service.ts    From enterprise-ng-2020-workshop with MIT License 6 votes vote down vote up
handleError(error: Error | HttpErrorResponse) {
    let displayMessage = 'An error occurred.';

    if (!environment.production) {
      displayMessage += ' See console for details.';
    }

    this.notificationsService.error(displayMessage);

    super.handleError(error);
  }
Example #29
Source File: error.interceptor.ts    From radiopanel with GNU General Public License v3.0 6 votes vote down vote up
intercept(
		request: HttpRequest<any>,
		next: HttpHandler
	): Observable<HttpEvent<any>> {
		return next.handle(request).pipe(
			catchError((error: HttpErrorResponse) => {
				this.toastr.error(pathOr('Something went wrong while trying to do that', ['error', 'message'])(error), 'Error');
				return throwError(error);
			})
		);
	}