rxjs#catchError TypeScript Examples
The following examples show how to use
rxjs#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: catchTxError.ts From anchor-web-app with Apache License 2.0 | 6 votes |
catchTxError = <TxResult>(
params: CatchTxErrorParams,
): OperatorFunction<TxResultRendering<TxResult>, any> => {
const { txErrorReporter } = params;
return catchError((error) => {
const errorId = txErrorReporter ? txErrorReporter(error) : error.message;
if (errorContains(error, TxError.TxAlreadyProcessed)) {
return Promise.resolve<TxResultRendering>({
value: null,
phase: TxStreamPhase.SUCCEED,
receipts: [],
});
}
if (errorContains(error, TxError.TxInvalid)) {
return formatTxErrorResult(error, errorId, TxError.TxInvalid);
}
if (errorContains(error, TxError.TxHashInvalid)) {
return formatTxErrorResult(error, errorId, TxError.TxHashInvalid);
}
return Promise.resolve<TxResultRendering>({
value: null,
phase: TxStreamPhase.FAILED,
failedReason: { error: error?.data?.message ?? error?.message, errorId },
receipts: [],
});
});
}
Example #2
Source File: options-addon-section.component.ts From WowUp with GNU General Public License v3.0 | 6 votes |
private onWagoEnable(option: MatListOption) {
const providerName: AddonProviderType = option.value;
const title: string = this._translateService.instant("DIALOGS.PERMISSIONS.WAGO.TOGGLE_LABEL");
const message: string = this._translateService.instant("DIALOGS.PERMISSIONS.WAGO.DESCRIPTION", {
termsUrl: AppConfig.wago.termsUrl,
dataUrl: AppConfig.wago.dataConsentUrl,
});
const dialogRef = this._dialogFactory.getConfirmDialog(title, message);
dialogRef
.afterClosed()
.pipe(
first(),
switchMap((result) => {
if (result) {
return from(this._addonProviderService.setProviderEnabled(providerName, option.selected));
} else {
option.selected = !option.selected;
}
return of(undefined);
}),
catchError((err) => {
console.error(err);
return of(undefined);
})
)
.subscribe();
}
Example #3
Source File: options-addon-section.component.ts From WowUp with GNU General Public License v3.0 | 6 votes |
public constructor(
private _addonProviderService: AddonProviderFactory,
private _sensitiveStorageService: SensitiveStorageService,
private _translateService: TranslateService,
private _dialogFactory: DialogFactory,
private _linkService: LinkService
) {
this._addonProviderService.addonProviderChange$.subscribe(() => {
this.loadProviderStates();
});
this.preferenceForm.valueChanges
.pipe(
takeUntil(this.destroy$),
debounceTime(300),
switchMap((ch) => {
const tasks: Observable<any>[] = [];
if (typeof ch?.cfV2ApiKey === "string") {
tasks.push(from(this._sensitiveStorageService.setAsync(PREF_CF2_API_KEY, ch.cfV2ApiKey)));
}
if (typeof ch?.ghPersonalAccessToken === "string") {
tasks.push(
from(this._sensitiveStorageService.setAsync(PREF_GITHUB_PERSONAL_ACCESS_TOKEN, ch.ghPersonalAccessToken))
);
}
return combineLatest(tasks);
}),
catchError((e) => {
console.error(e);
return of(undefined);
})
)
.subscribe();
}
Example #4
Source File: wowup-protocol.service.ts From WowUp with GNU General Public License v3.0 | 6 votes |
public initialize() {
this._electronService.customProtocol$
.pipe(
tap((prt) => console.log("WowUpProtocolService", prt)),
filter((prt) => getProtocol(prt) === APP_PROTOCOL_NAME && this.isInstallAction(prt)),
switchMap((prt) => this.onInstallProtocol(prt)),
catchError((e) => {
console.error(e);
return of(undefined);
})
)
.subscribe();
}
Example #5
Source File: auth.ts From bext with MIT License | 6 votes |
octokit$
.pipe(
switchMap((octokit) =>
octokit
? from(octokit.rest.users.getAuthenticated()).pipe(
map(({ data, status }) =>
status === 200
? ({ status: 'complete', user: data } as const)
: ({ status: 'error' } as const),
),
startWith({ status: 'loading' } as const),
retry(2),
catchError(() => of({ status: 'error' } as const)),
)
: of({ status: 'unauth' } as const),
),
)
.subscribe(user$);
Example #6
Source File: datadog.interceptor.ts From ironfish-api with Mozilla Public License 2.0 | 6 votes |
intercept(
context: ExecutionContext,
next: CallHandler<unknown>,
): Observable<unknown> {
const start = new Date().getTime();
return next.handle().pipe(
tap(() => {
const duration = new Date().getTime() - start;
const request = context.switchToHttp().getRequest<Request>();
if (!request) {
return;
}
this.datadogService.timing('requests.success', duration, {
method: request.method,
path: request.path,
});
}),
catchError((error: Error) => {
let method = 'no-method';
let path = 'no-path';
const request = context.switchToHttp().getRequest<Request>();
if (request) {
method = request.method;
path = request.path;
}
this.datadogService.increment('requests.error', 1, {
method,
path,
type: error.constructor.name,
});
return throwError(() => error);
}),
);
}
Example #7
Source File: peer.service.ts From onchat-web with Apache License 2.0 | 6 votes |
createOffer(options?: RTCOfferOptions) {
return from(this.connection.createOffer(options)).pipe(
catchError(error => {
this.overlay.toast('WebRTC Offer 创建失败!');
console.error(error);
return throwError(() => error);
})
);
}
Example #8
Source File: peer.service.ts From onchat-web with Apache License 2.0 | 6 votes |
createAnswer(options?: RTCAnswerOptions) {
return from(this.connection.createAnswer(options)).pipe(
catchError(error => {
this.overlay.toast('WebRTC Answer 创建失败!');
console.error(error);
return throwError(() => error);
})
);
}
Example #9
Source File: FormData.interceptor.ts From nestjs-form-data with MIT License | 5 votes |
async intercept(context: ExecutionContext, next: CallHandler<any>): Promise<any> {
const req = context.switchToHttp().getRequest();
const res = context.switchToHttp().getResponse();
/** if the request is not multipart, skip **/
if (!is(req, ['multipart'])) return next.handle();
/** merge global config with method level config **/
const config: FormDataInterceptorConfig = checkConfig(
this.reflector.get(FORM_DATA_REQUEST_METADATA_KEY, context.getHandler()) || {},
this.globalConfig,
);
const formReader: FormReader = new FormReader(req, config);
return from(formReader.handle()).pipe(
mergeMap((formReaderResult: any) => {
req.body = formReaderResult;
return next.handle();
}),
catchError(err => {
if (config.autoDeleteFile)
formReader.deleteFiles();
if (err.status && err.response) {
res.status(err.status);
return of(err.response);
}
return throwError(err);
}),
tap(res => {
if (config.autoDeleteFile)
formReader.deleteFiles();
}),
);
}
Example #10
Source File: publish-list.tsx From bext with MIT License | 5 votes |
PublishList: FC = () => (
<div className="py-3">
{useObservableState(
useObservable(() =>
user$.pipe(
switchMap(({ status, user }) => {
switch (status) {
case 'loading':
return of(<Spinner />);
case 'complete':
const octokit = octokit$.getValue()!;
return timer(0, REFRESH_DURATION).pipe(
switchMap(() =>
from(
octokit.paginate(octokit.search.issuesAndPullRequests, {
q: `is:pr author:${user?.login} repo:${packageJson.metaRepository.owner}/${packageJson.metaRepository.repo}`,
sort: 'created',
order: 'desc',
}),
).pipe(
map((items) => (
<>
<Banner current={Date.now()} empty={!items.length} />
{items.length ? (
<List
items={items}
onRenderCell={(item) => <PrItem item={item!} />}
/>
) : null}
</>
)),
retry(2),
catchError(() =>
of(<div className="text-center">出错了...</div>),
),
),
),
);
default:
return of(
<div className="text-center">
<LoginLink /> 后查看发布历史
</div>,
);
}
}),
startWith(<Spinner />),
),
),
) || null}
</div>
)
Example #11
Source File: publish-dialog.tsx From bext with MIT License | 4 votes |
PublishDialog: FC<{ hide?: () => void }> = ({ hide }) => {
const { draft } = useDraft();
const { notify, dismissNotification } = useNotifications();
const [message, setMessage] = useState('');
const [loading, setLoading] = useState(false);
const onPublish = () => {
const notifyId = uniqueId('export-notify');
const loading = (message: string) =>
notify({
status: 'loading',
message,
dismissAfter: 0,
dismissible: false,
id: notifyId,
});
const branchName = Math.random().toString(16).slice(2);
const user = user$.getValue()!.user!;
const octokit = octokit$.getValue()!;
setLoading(true);
of(draft!)
.pipe(
switchMap((draft) => {
if (!(draft.id && draft.name && draft.version)) {
return throwError(() => new Error('请填写完整 ID,名称,版本号'));
}
loading('编译中');
return from(
excuteCompile({
meta: {
id: draft.id,
name: draft.name,
version: draft.version!,
source: draft.source!,
defaultConfig: draft.defaultConfig,
},
}),
).pipe(
catchError(() =>
throwError(() => new Error('编译错误,请打开控制台查看详情')),
),
switchMap(() => {
loading('获取仓库信息');
return from(
octokit.repos.get({
owner: user.login!,
repo: packageJson.metaRepository.repo,
}),
).pipe(
catchError((error) => {
if (error.status === 404) {
loading('Fork 仓库');
return from(
octokit.repos.createFork({
owner: packageJson.metaRepository.owner,
repo: packageJson.metaRepository.repo,
}),
).pipe(
concatMap(() => {
loading('查询 Fork 结果');
return timer(5000, 10000).pipe(
switchMap(() =>
from(
octokit.repos.get({
owner: user.login!,
repo: packageJson.metaRepository.repo,
}),
).pipe(catchError(() => EMPTY)),
),
take(1),
);
}),
);
}
return throwError(() => new Error('查询仓库信息失败'));
}),
);
}),
switchMap(({ data: repo }) => {
loading('创建分支');
return from(
octokit.git.createRef({
owner: repo.owner.login,
repo: repo.name,
ref: `refs/heads/${branchName}`,
sha: packageJson.metaRepository.base,
}),
);
}),
switchMap(() => {
loading('同步主分支');
return from(
octokit.repos.mergeUpstream({
owner: user.login!,
repo: packageJson.metaRepository.repo,
branch: branchName,
}),
);
}),
switchMap(() => {
loading('获取文件信息');
return from(
octokit.repos.getContent({
owner: user.login,
repo: packageJson.metaRepository.repo,
path: `meta/${draft.id}.json`,
ref: branchName,
}),
).pipe(
map(({ data }) =>
Array.isArray(data) ? data[0].sha : data.sha,
),
catchError((err) =>
err?.status === 404 ? of(undefined) : throwError(() => err),
),
);
}),
switchMap((sha) => {
const prepareDraft = omit(cloneDeep(draft), 'id');
prepareDraft.detail = DOMPurify.sanitize(
prepareDraft.detail || '',
);
return from(
octokit.repos.createOrUpdateFileContents({
owner: user.login,
repo: packageJson.metaRepository.repo,
path: `meta/${draft.id}.json`,
message,
content: Base64.encode(JSON.stringify(prepareDraft)),
sha,
branch: branchName,
}),
);
}),
switchMap(() =>
from(
octokit.pulls.create({
owner: packageJson.metaRepository.owner,
repo: packageJson.metaRepository.repo,
title: `[${draft.name}] ${draft.synopsis}`,
head: `${user.login}:${branchName}`,
base: 'master',
maintainer_can_modify: true,
}),
),
),
);
}),
finalize(() => {
dismissNotification(notifyId);
setLoading(false);
hide?.();
}),
catchError((err) => {
notify({
status: 'error',
message: err?.message || err?.toString(),
dismissible: true,
dismissAfter: 3000,
});
return EMPTY;
}),
)
.subscribe(() => {
notify({
status: 'success',
message: '提交成功,请返回查看、预览',
});
});
};
return (
<>
<TextField
description="将会在切换版本时展示"
value={message}
onChange={(_, text) => setMessage(text || '')}
disabled={loading}
/>
<DialogFooter>
<PrimaryButton
className="ml-auto"
onClick={onPublish}
disabled={loading || !message.length}
>
发布
</PrimaryButton>
</DialogFooter>
</>
);
}