使用全局错误处理程序处理 NGXS(角度)中的错误

cma*_*art 7 angular ngxs

我想用两种方式处理 NGXS 中的错误。第一种方法是处理组件中存储调度的错误。第二种方法是全局角度错误处理程序,作为错误未处理时的后备(第一种方法未处理)。

但问题是,当操作处理程序中出现错误时,NGRX 总是会调用全局错误处理程序。

因此,在组件中给出以下代码:

this.store.dispatch(new FetchAction())
   .subscribe( error: () => console.log('fetch error occured'))
Run Code Online (Sandbox Code Playgroud)

这个动作处理程序:

fetch() {
   return this.http.get('..');
}
Run Code Online (Sandbox Code Playgroud)

和这个全局错误处理程序:

export class GlobalErrorHandler extends ErrorHandler {
   handleError(err: any) {
      console.log('unexpected error occured');
   }
}
Run Code Online (Sandbox Code Playgroud)

控制台中会出现两条错误消息。一份来自调度的订阅,一份来自全局错误处理程序,因为操作处理程序中存在错误。

现在我可以在操作处理程序中捕获错误,但这将是错误的地方,因为操作处理程序不应该知道该操作的错误是在组件中处理的。

我做了一个 stackblitz,单击按钮时在控制台中显示两个错误:https ://stackblitz.com/edit/ngxs-error-throw-r42fkb?file=src/app/app.component.ts

Max*_*nas 1

使用 RxJScatchError运算符处理低级别的错误:

这样,您就捕获了错误,因此它不会调用您的全局操作处理程序。

this.store.dispatch(new FetchAction())
   .pipe(catchError(error => /* Do something specific with the error. */))
   .subscribe(() => { /* Do something with the success result. */ })
Run Code Online (Sandbox Code Playgroud)

让错误向上冒泡到全局操作处理程序:

这里没什么特别的。只需忽略该错误即可。当您不知道如何处理错误时,请执行此操作。

this.store.dispatch(new FetchAction())
   .subscribe(() => { /* Do something with the success result. */ })
Run Code Online (Sandbox Code Playgroud)

如果需要,您可以重新抛出更具体的错误,throwError以便在更高级别处理该错误时获得更多信息。

this.store.dispatch(new FetchAction())
   .pipe(catchError(error => throwError(new Error('Some specific error.'))))
   .subscribe(() => { /* Do something with the success result. */ })
Run Code Online (Sandbox Code Playgroud)

  • “这样,您就捕获了错误,因此它不会调用您的全局操作处理程序。” 我猜你的意思是全局错误处理程序。但这正是重点。当 ngxs 操作处理程序中出现错误时,这仍然会调用全局错误处理程序。如果您没有 catchError 并且只是订阅全局错误处理程序,那么实际上会调用两次。 (2认同)