【问题标题】:Angular Error Handling - catchError does not return an error object for rxjs effectAngular 错误处理 - catchError 不为 rxjs 效果返回错误对象
【发布时间】:2021-05-13 13:52:34
【问题描述】:

我一直致力于在 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

【问题讨论】:

  • 抱歉,你能澄清一下问题是什么并用这个更新问题吗?
  • 我刚刚编辑了这个问题,先生。 @安德鲁艾伦

标签: angular asp.net-core rxjs ngrx


【解决方案1】:

我在不同的帖子中看到了一种类似的捕获错误的方法,它也有同样的问题,即没有返回 catchError 操作。相信这篇文章总结的很好Handling Errors in 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)))
  )
);

【讨论】:

    猜你喜欢
    • 2020-10-07
    • 1970-01-01
    • 2013-01-23
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 2020-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多