You need to enable JavaScript to run this app. 如何使用switchMap、pipe、map、catchError实现错误处理泛型辅助工具
优惠活动
大模型
产品
解决方案
定价
更多

如何使用switchMap、pipe、map、catchError实现错误处理泛型辅助工具

你的思路是可行的,只需要修正原有初步实现的几个问题,补充TypeScript泛型约束即可投入使用,完整方案如下:

通用Effect辅助方法实现

import { Actions, createEffect, ofType } from '@ngrx/effects';
import { Action, ActionCreator } from '@ngrx/store';
import { catchError, map, switchMap } from 'rxjs/operators';
import { of, Observable } from 'rxjs';

// 泛型参数说明
// TTrigger: 触发effect的action类型
// TApiResponse: API接口返回值类型
// TSuccessAction: 成功回调返回的action类型
// TFailureAction: 失败回调返回的action类型
export class EffectHelper {
  public static create<
    TTrigger extends Action,
    TApiResponse,
    TSuccessAction extends Action,
    TFailureAction extends Action
  >(
    actions$: Actions,
    triggerAction: ActionCreator,
    apiCall: (actionArgs: TTrigger) => Observable<TApiResponse>,
    successActionCreator: (response: TApiResponse) => TSuccessAction,
    failureActionCreator: (error: unknown) => TFailureAction = (error) => ({
      type: '[通用] 加载失败',
      error: 'fail'
    } as TFailureAction)
  ) {
    return createEffect(() => 
      actions$.pipe(
        ofType(triggerAction),
        switchMap((action: TTrigger) => 
          apiCall(action).pipe(
            map((response) => successActionCreator(response)),
            catchError((err) => of(failureActionCreator(err)))
          )
        )
      )
    );
  }
}

原初步实现的问题说明

  • 未接收action参数:部分API调用需要从触发action中取参数(比如示例中的getSettingsByNamesForUser需要args.settingNames),原实现直接传入固定的api调用逻辑无法适配这类场景
  • 缺少泛型约束:没有类型声明会导致TypeScript的类型校验失效,使用时容易传错参数
  • 操作符结构错误:原实现中switchMap的参数结构不对,且catchError没有返回of()包裹的安全Observable,会导致effect流在请求出错后直接终止,后续无法再响应对应action

使用示例

将你原有的重复代码替换为辅助方法调用即可,写法如下:

// 无参数的effect
loadBasicStateInfo$ = EffectHelper.create(
  this.actions$,
  actions.loadBasicStateInfo,
  () => this.configurationService.getBasicStateInfo(),
  (response) => actions.loadBasicStateInfoComplete({ 
    basicStateInfo: new BasicStateInfo(response.result) 
  }),
  () => actions.loadBasicStateInfoFailure({ error: 'fail' })
);

// 携带参数的effect
loadSetting$ = EffectHelper.create(
  this.actions$,
  actions.loadSettings,
  (action) => this.configurationService.getSettingsByNamesForUser(action.settingNames),
  (response) => actions.loadSettingsCompleted({ settings: response.result }),
  () => actions.loadSettingsFailure({ error: 'fail' })
);

如果你的失败逻辑都是统一返回{error: 'fail'},还可以进一步把失败回调的默认值配置成适配你项目的统一逻辑,不用每次都传失败回调,进一步减少重复代码。


内容的提问来源于stack exchange,提问作者Mauricio Gracia Gutierrez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 10:54:05