将 subscribe()
方法与 catch()
一起使用时,我能够捕获异常,但这是在服务调用的基础上完成的。
有没有办法捕获页面中任何地方发生的异常并将其显示在 View 中?
捕获异常并将其显示在控制台中很简单,但我需要在 View 中显示一些内容以提供有用的错误消息,而不是仅仅卡住。
谢谢
最佳答案
您可以覆盖模块内的全局错误处理程序:
https://angular.io/docs/ts/latest/api/core/index/ErrorHandler-class.html
import { NgModule, ErrorHandler } from '@angular/core';
class MyErrorHandler implements ErrorHandler {
handleError(error) {
// do something with the exception
}
}
@NgModule({
providers: [{ provide: ErrorHandler, useClass: MyErrorHandler }]
})
class MyModule {}
对于自定义错误对话框或错误消息,我将创建一个自定义 ErrorLogService,它允许组件订阅错误事件。显示错误的组件会订阅错误事件,并显示错误消息,或者弹出错误对话框。
请参阅此答案,了解如何使用 Flux 来执行此操作(模式很重要 - 而不是涉及的特定类): How can I maintain the state of dialog box with progress all over my Angular 2 application?
关于angular - 捕获异常并在 View 中显示错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42222633/