2017-02-14 50 views
2

當catch()方法使用.subscribe()方法時,我能夠捕獲異常,但是這是在服務調用的基礎上完成的。有什麼辦法可以捕獲頁面中任何地方發生的異常並將其顯示在視圖中?Angular2 - 捕獲異常並在視圖中顯示錯誤消息

直接捕獲異常並將它們顯示在控制檯中,但我需要在視圖中顯示某些內容以提供有用的錯誤消息,而不是僅凍結。

感謝

+0

您可以使用[window.onerror(HTTPS://developer.mozilla。 org/en-US/docs/Web/API/GlobalEventHandlers/onerror)對網頁上的所有異常做出反應,但我不確定這是個好主意...... – AngularChef

回答

2

您可以在模塊內覆蓋全局錯誤處理程序:

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,這使得組件來訂閱錯誤事件。顯示錯誤的組件將訂閱錯誤事件,並顯示錯誤消息,或彈出錯誤對話框。

看到這個答案如何利用流量做這個(模式是很重要的 - 不涉及具體的類): How can I maintain the state of dialog box with progress all over my Angular 2 application?

相關問題