首页 > 解决方案 > Angular 错误处理 - catchError 不为 rxjs 效果返回错误对象

问题描述

我一直致力于在 Facebook 等社交媒体网站上创建帖子的错误处理过程。当用户尝试创建帖子,但后端服务器为该进程返回错误时,用户必须看到错误。

如果后端服务器返回错误,则必须触发catchError函数。之后,必须使用 reducer 填充一个称为 PostState 的状态。

如果创建 post 过程失败,并且后端服务器为此过程返回错误,则 PostActionTypes.CreatePostFail情况必须为 postReducer 工作。

PostActionTypes.CreatePostSuccess在有或没有错误的情况下都有效。

我无法使用 Ngrx 效果处理错误过程。

如何使用 Ngrx 效果处理错误过程?

export interface PostState {
showPostId: boolean;
currentPost: Post;
currentPostId: number;
posts: Post[];
commentPost: Post;
isNewPost: boolean;
error: string;
isNewComment: boolean; }

const initialState: PostState = {
showPostId: true,
currentPost: null,
currentPostId: null,
posts: [],
commentPost: null,
isNewPost: false,
error: '',
isNewComment: false };

export function postReducer(state = initialState, action: PostActions): PostState {
switch (action.type) {

    case PostActionTypes.CreatePost:
        return {
            ...state,
            isNewPost: true
        };

    case PostActionTypes.CreatePostSuccess:
        return {
            ...state,
            posts: [...state.posts, action.payload].sort((a, b) => <any>new Date(b.createdDate) - <any>new Date(a.createdDate)),
            error: '',
            isNewPost: false
        };

    case PostActionTypes.CreatePostFail:
        return {
            ...state,
            error: action.payload,
            isNewPost: false
        };

    default:
        return state;
}

}

这是我的 createPost 服务实现。

createPost(post: any): Observable<Post> {
const headers = new HttpHeaders
  ({
    "Authorization": "Bearer " + this.authService.getToken
  });
return this.http.post(this.postUrl + "createpost", post, { headers: headers })
  .pipe(
    tap((data: any) => { console.log(data) }),
    catchError(this.handleError)
  ); }

这是handleError函数的实现。

private handleError(err: any) {
let errorMessage: string;
if (err.error instanceof ErrorEvent) {
  errorMessage = `An error occurred: ${err.error.message}`;
} else {
  errorMessage = `Backend returned code ${err.status}: ${err.body.error}`;
}
console.error(err);
return throwError(errorMessage); }

您可以在下面看到 createPost$ 效果实现。

   @Effect()
createPost$: Observable<Action> = this.actions$.pipe(
    ofType(postActions.PostActionTypes.CreatePost),
    map(((action: postActions.CreatePost) => action.payload)),
    mergeMap((post: any) =>
        this.postService.createPost(post).pipe(
            map((newPost: any) => (new postActions.CreatePostSuccess(newPost.result))),
            catchError(err => of(new postActions.CreatePostFail(err)))
        )
    )
);

这是后端服务器错误的示例

在此处输入图像描述

如果您想检查该项目,可以在下面查看 Github 存储库。

https://github.com/dogaanismail/DevPlatform/tree/master/DevPlatform.Api/DevPlatformSpa

标签: angularasp.net-corerxjsngrx

解决方案


我在不同的帖子中看到了一种类似的方法来捕获错误,它也有同样的问题,即catchError没有返回操作。我相信这篇文章很好地总结了NgRx Effects 中的错误处理

TLDR:尝试并在流switchMap之外捕获错误createPost

@Effect
createPost$: Observable<Action> = this.actions$.pipe(
  ofType(postActions.PostActionTypes.CreatePost),
  map((action: postActions.CreatePost) => action.payload),
  switchMap((post: any) =>
    this.postService.createPost(post).pipe(
      map((newPost: any) => new postActions.CreatePostSuccess(newPost.result)),
    ),
    catchError(err => (new postActions.CreatePostFail(err)))
  )
);

推荐阅读