我想以两种方式处理 NGXS 中的错误。第一种方法是处理组件中 store dispatch 的错误。第二种方式是全局 Angular 错误处理程序,作为错误未处理(未通过第一种方式处理)时的回退。
但问题在于,当 Action 处理程序出现错误时,NGRX 总是会调用全局错误处理程序。
所以给定组件中的这段代码:
this.store.dispatch(new FetchAction())
.subscribe( error: () => console.log('fetch error occured'))
这个 Action 处理程序:
fetch() {
return this.http.get('..');
}
和这个全局错误处理程序:
export class GlobalErrorHandler extends ErrorHandler {
handleError(err: any) {
console.log('unexpected error occured');
}
}
控制台中会有两条错误消息。一个来自调度的订阅,一个来自全局错误处理程序,因为操作处理程序中存在错误。
现在我可以在 Action 处理程序中捕获错误,但这将是错误的地方,因为 Action 处理程序不应该知道来自该 Action 的错误是在组件中处理的。
我做了一个 stackblitz,它在单击按钮时在控制台中显示了两个错误:https://stackblitz.com/edit/ngxs-error-throw-r42fkb?file=src/app/app.component.ts
最佳答案
使用 RxJS catchError
运算符(operator)在低级别处理错误:
这样,您就捕获了错误,因此它不会调用您的全局操作处理程序。
this.store.dispatch(new FetchAction())
.pipe(catchError(error => /* Do something specific with the error. */))
.subscribe(() => { /* Do something with the success result. */ })
让错误冒泡到全局操作处理程序:
这里没什么特别的。只需忽略错误。
当您不知道如何处理错误时,请执行此操作。
this.store.dispatch(new FetchAction())
.subscribe(() => { /* Do something with the success result. */ })
如果您愿意,可以使用
throwError
重新抛出更具体的错误。所以当你在更高的层次上处理它时,你会有更多的信息。this.store.dispatch(new FetchAction())
.pipe(catchError(error => throwError(new Error('Some specific error.'))))
.subscribe(() => { /* Do something with the success result. */ })
关于angular - 使用全局错误处理程序处理 NGXS (angular) 中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56872587/