寫在前面
代碼寫得再好,始終都無法完整的處理所有可能產(chǎn)生異常,特別是生產(chǎn)環(huán)境中的應(yīng)用,很大一部分是數(shù)據(jù)來自用戶、遠(yuǎn)程,很難保證所有數(shù)據(jù)都按程序規(guī)定的產(chǎn)生。事實(shí)上,除非測試人員發(fā)現(xiàn)或者客戶報告,否則都無法得知。因此,將應(yīng)用產(chǎn)生的未可知異常進(jìn)而上報是非常重要的環(huán)節(jié)。
Angular 默認(rèn)情況下也提供了全局的異常管理,當(dāng)發(fā)生異常時,會把它扔到 Console 控制臺上。如果你在使用 NG-ZORRO 時,可能經(jīng)常就會遇到 ICON 未加載的異常消息,這也是異常消息的一種:
1
2
3
4
5
6
7
8
9
10
11
|
core.js:5980 ERROR Error: [@ant-design/icons-angular]:the icon setting-o does not exist or is not registered. at IconNotFoundError (ant-design-icons-angular.js:94) at MapSubscriber.project (ant-design-icons-angular.js:222) at MapSubscriber._next (map.js:29) at MapSubscriber.next (Subscriber.js:49) at RefCountSubscriber._next (Subscriber.js:72) at RefCountSubscriber.next (Subscriber.js:49) at Subject.next (Subject.js:39) at ConnectableSubscriber._next (Subscriber.js:72) at ConnectableSubscriber.next (Subscriber.js:49) at CatchSubscriber.notifyNext (innerSubscribe.js:42) |
而 Angular 是通過 ErrorHandler 統(tǒng)一管理異常消息,而且只需要覆蓋其中的 handleError 方法并重新處理異常消息即可。
ErrorHandler
首先創(chuàng)建一個 custom-error-handler.ts 文件:
1
2
3
4
5
6
7
8
|
import { ErrorHandler, Injectable } from '@angular/core' ; @Injectable() export class CustomErrorHandler extends ErrorHandler { handleError(error: any): void { super .handleError(error); } } |
CustomErrorHandler 可以完整的獲取當(dāng)前用戶數(shù)據(jù)、當(dāng)前異常消息對象等,并允許通過 HttpClient 上報給后端。
以下是 NG-ALAIN 的文檔站,由于是使用 Google Analytics 來分析,只需要將異常消息轉(zhuǎn)給 onerror 即可:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
import { DOCUMENT } from '@angular/common'; import { ErrorHandler, Inject, Injectable } from '@angular/core'; @Injectable() export class CustomErrorHandler extends ErrorHandler { constructor(@Inject(DOCUMENT) private doc: any) { super(); } handleError(error: any): void { try { super.handleError(error); } catch (e) { this.reportError(e); } this.reportError(error); } private reportError(error: string | Error ): void { const win = this.doc.defaultView as any; if (win && win.onerror) { if (typeof error === 'string') { win.onerror(error); } else { win.onerror(error.message, undefined, undefined, undefined, error); } } } } |
最后,在 AppModule 模塊內(nèi)注冊 CustomErrorHandler :
1
2
3
4
5
6
|
@NgModule({ providers: [ { provide: ErrorHandler, useClass: CustomErrorHandler }, ] }) export class AppModule { } |
結(jié)論
事實(shí)上還有一項(xiàng)非常重要的工作,生產(chǎn)環(huán)境中都是打包壓縮過后的,換言之所產(chǎn)生的異常消息也是無法與實(shí)際代碼行數(shù)相同的數(shù)字,這就需要 SourceMap 的支持,當(dāng)然正常的生產(chǎn)環(huán)境是不會發(fā)布這份文件的,所以如果想要得到正確的行列數(shù),還是需要借助一層中間層,在后端利用 source-map 模塊來解析出真正的行列數(shù)值。
Angular 的依賴注入(DI)系統(tǒng)可以使我們快速替換一些 Angular 內(nèi)置模塊,從而實(shí)現(xiàn)在不修改業(yè)務(wù)層面時快速解決一些特殊需求。
總結(jié)
到此這篇關(guān)于Angular如何處理未可知異常錯誤的文章就介紹到這了,更多相關(guān)Angular處理未可知異常錯誤內(nèi)容請搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://segmentfault.com/a/1190000038999559