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: erc20.helper.ts From gnosis.1inch.exchange with MIT License | 6 votes |
public getApprovedAmount(
contractAddress: string,
walletAddress: string,
spender: string,
blockNumber?: number
): Observable<BigNumber> {
return this.getERC20Instance(contractAddress).pipe(
mergeMap((instance) => {
const call$ = instance.methods.allowance(
walletAddress,
spender
).call(null, blockNumber || 'pending')
.then((x) => {
return x !== null ? x : zeroValueBN;
});
return fromPromise(call$) as Observable<BigNumber>;
}),
catchError(() => {
return of(zeroValueBN);
}),
take(1)
);
}
Example #2
Source File: _catchTxError.ts From anchor-web-app with Apache License 2.0 | 6 votes |
export function _catchTxError({
helper,
txErrorReporter,
}: Params): OperatorFunction<any, any> {
return catchError((error) => {
const errorId =
txErrorReporter &&
!(error instanceof UserDenied || error instanceof Timeout)
? txErrorReporter(error)
: undefined;
return Promise.resolve<TxResultRendering>({
value: null,
phase: TxStreamPhase.FAILED,
failedReason: { error, errorId },
receipts: [helper.txHashReceipt()],
});
});
}
Example #3
Source File: unauthorized.interceptor.ts From Smersh with MIT License | 6 votes |
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 #4
Source File: liquidity-pools.service.ts From xBull-Wallet with GNU Affero General Public License v3.0 | 6 votes |
// 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: cross-chain-routing-api.service.ts From rubic-app with GNU General Public License v3.0 | 6 votes |
/**
* post trade with domain query {@link RubicExchangeInterceptor} to save extended trade info in backend
* @param transactionHash hash of crosschain swap transaction
* @param blockchain swap origin blockchain
* @param [promoCodeText] promo code text if promo code has been successfully applied
*/
public postTrade(
transactionHash: string,
blockchain: BlockchainName,
promoCodeText?: string
): Promise<void> {
const network = TO_BACKEND_BLOCKCHAINS[blockchain];
return this.httpService
.patch<void>('trades/', { transactionHash, network, promoCode: promoCodeText }, {}, BASE_URL)
.pipe(
catchError((err: unknown) => {
console.error(err);
return of(undefined);
})
)
.toPromise();
}
Example #6
Source File: product.service.ts From Angular-ActionStreams with MIT License | 6 votes |
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 #7
Source File: product.service.ts From Angular-HigherOrderMapping with MIT License | 6 votes |
// Simple map doesn't work
productWithMap$ = this.productSelectedAction$
.pipe(
map(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 #8
Source File: index.ts From dbm with Apache License 2.0 | 6 votes |
/* ----------------------------------------------------------------------------
* 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 #9
Source File: ajax-flow.ts From RcloneNg with MIT License | 6 votes |
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 #10
Source File: epic.ts From Shopping-Cart with MIT License | 6 votes |
fetchProductListEpic: Epic = (
action$: ActionsObservable<Actions>,
_,
{ productService }: Service,
) =>
action$.pipe(
filter(isActionOf(fetchProductListAsync.request)),
switchMap(({ payload }) => {
const { items, totalProducts } = productService.getItems(
payload.currentPage,
);
return of(fetchProductListAsync.success({ items, totalProducts }));
}),
catchError(err => {
return of(fetchProductListAsync.failure(err));
}),
)
Example #11
Source File: location-api.service.ts From mylog14 with GNU General Public License v3.0 | 6 votes |
getReverseGeocoding(latitude: number, longitude: number): Observable<any> {
const endpoint = this.baseUrl + '/reverse';
return this.dataStore.userData$
.pipe(
take(1),
map(userData => this.createReverseGeocodingParams(latitude, longitude, userData.language)),
switchMap(params => this.httpClient.get<ReverseGeocoderResponse>(endpoint, { params })),
map(response => `${response.address.suburb}, ${response.address.city}`),
catchError(error => {
console.error(error);
return of('');
})
);
}
Example #12
Source File: assets.service.ts From nica-os with MIT License | 6 votes |
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 #13
Source File: app.effects.ts From Angular-Cookbook with MIT License | 6 votes |
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 #14
Source File: grocy-api.component.ts From pantry_party with Apache License 2.0 | 6 votes |
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 #15
Source File: exception.interceptor.ts From domain-driven-hexagon with MIT License | 6 votes |
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 #16
Source File: message-broker.ts From scion-microfrontend-platform with Eclipse Public License 2.0 | 6 votes |
/**
* 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 #17
Source File: emote-list.component.ts From App with MIT License | 6 votes |
getEmotes(page = 0, options?: Partial<RestV2.GetEmotesOptions>): Observable<EmoteStructure[]> {
this.emotes.next([]);
this.newPage.next(page);
const timeout = setTimeout(() => this.loading.next(true), 1000);
const cancelSpinner = () => {
this.loading.next(false);
clearTimeout(timeout);
};
const size = this.calculateSizedRows();
return this.restService.awaitAuth().pipe(
switchMap(() => this.restService.v2.SearchEmotes(
(this.pageOptions?.pageIndex ?? 0) + 1,
Math.max(EmoteListComponent.MINIMUM_EMOTES, size ?? EmoteListComponent.MINIMUM_EMOTES),
options ?? this.currentSearchOptions
)),
takeUntil(this.newPage.pipe(take(1))),
tap(res => this.totalEmotes.next(res?.total_estimated_size ?? 0)),
delay(200),
map(res => res?.emotes ?? []),
mergeAll(),
map(data => this.dataService.add('emote', data)[0]),
toArray(),
defaultIfEmpty([] as EmoteStructure[]),
tap(() => cancelSpinner()),
catchError(() => defer(() => cancelSpinner()))
) as Observable<EmoteStructure[]>;
}
Example #18
Source File: base-user-apollo.service.ts From svvs with MIT License | 6 votes |
// 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 #19
Source File: curse-addon-provider.ts From WowUp with GNU General Public License v3.0 | 6 votes |
private getByIdBase(addonId: string): Observable<CurseSearchResult | undefined> {
const url = `${API_URL}/addon/${addonId}`;
return from(this._circuitBreaker.getJson<CurseSearchResult>(url)).pipe(
catchError((e) => {
// We want to eat things like 400/500 responses
console.error(e);
return of(undefined);
})
);
}