简体   繁体   English

Angular 错误处理 - catchError 不返回错误 object 用于 rxjs 效果

[英]Angular Error Handling - catchError does not return an error object for rxjs effect

I have been working on error handling process for creating a post in a social media website like facebook.我一直致力于在 facebook 等社交媒体网站上创建帖子的错误处理过程。 When a user tries to create a post, but the backend server returns an error for that process, the user must see the error.当用户尝试创建帖子,但后端服务器为该进程返回错误时,用户必须看到错误。

If the backend server returns an error, catchError function must be triggered.如果后端服务器返回错误,则必须触发catchError function。 After that, a state that is called PostState must be filled by using reducer.之后,必须使用reducer填充一个名为PostState的state。

If create post process has a fail, and the backend server returns an error for this process, PostActionTypes.CreatePostFail case must be worked for postReducer.如果创建 post 过程失败,并且后端服务器为此过程返回错误,则 PostActionTypes.CreatePostFail情况必须为 postReducer 工作。

PostActionTypes.CreatePostSuccess works with or without an error. PostActionTypes.CreatePostSuccess在有或没有错误的情况下都有效。

I can not handle error process by using Ngrx effect.我无法使用 Ngrx 效果处理错误过程。

How can I handle error process by using Ngrx effects?如何使用 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;
}

} }

Here is my createPost service implementations.这是我的 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)
  ); }

Here is handleError function implementations.这是 handleError function 实现。

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); }

You can see createPost$ effect implementations below.您可以在下面看到 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)))
        )
    )
);

Here is an example of a backend server error这是后端服务器错误的示例

在此处输入图像描述

If you would like to examine the project, you can see the Github repo in the below.如果您想检查该项目,可以在下面查看 Github 存储库。

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

I've seen a similar approach to catching errors in a different post and it had the same problem, that the catchError action was not returned.我在不同的帖子中看到了一种类似的捕获错误的方法,它也有同样的问题,即没有返回catchError操作。 I believe this article sums it up nicely Handling Errors in NgRx Effects .我相信这篇文章很好地总结了NgRx Effects 中的错误处理

TLDR: Try it with switchMap and catch error outside of the createPost stream TLDR:尝试使用switchMap并在createPost stream 之外捕获错误

@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)))
  )
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM