node 10.15.0
ionic 4.12.0
cordova 9.0
# platforms
cordova-android:8.0.0
cordova-ios: 5.0.0
前言
Angular2+使用TypeScript語言,經(jīng)編譯器轉(zhuǎn)換后生成的代碼基本無可讀性,所以如果需要查看詳細(xì)錯(cuò)誤信息,還需要在打包時(shí)配置source-map
"prod": "ng build --aot=true --prod --source-map=true"
# 或者 angular.json
configurations -> production -> sourceMap : true
為什么需要捕捉全局異常?
在實(shí)際應(yīng)用場景中,當(dāng)程序發(fā)生錯(cuò)誤時(shí),我們需要第一時(shí)間知道,而不是由客戶發(fā)現(xiàn),這樣就需要一個(gè)日志上報(bào)功能(其他日志不在本文討論范圍內(nèi));那我們只需在全局捕捉到錯(cuò)誤,然后將一些必要信息上傳到后端,最后進(jìn)行分析排查,解決問題。
如何捕捉?
定義GlobalErrorHandler類
import { ErrorHandler, Injectable, Injector } from '@angular/core';
import { LocationStrategy, PathLocationStrategy } from '@angular/common';
import { NGXLogger } from 'ngx-logger';
import * as StackTrace from 'stacktrace-js';
/**
* 全局異常處理
*/
@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
constructor(private injector: Injector) { }
handleError(error) {
const loggingService = this.injector.get(NGXLogger);
const location = this.injector.get(LocationStrategy);
const message = error.message ? error.message : error.toString();
const url = location instanceof PathLocationStrategy ? location.path() : '';
// get the stack trace, lets grab the last 10 stacks only
StackTrace.fromError(error).then(stackframes => {
const stackString = stackframes
.splice(0, 20)
.map(function(sf) {
return sf.toString();
}).join('\n');
console.log(stackString);
loggingService.error('error', {message: message, stack: stackString});
});
throw error;
}
}
第三方庫:
- stacktrace-js 堆棧追蹤
- ngx-logger 日志(支持發(fā)送到服務(wù)器)
第一步
實(shí)現(xiàn)ErrorHandler的handleError方法
第二步
堆棧追蹤,利用stacktrace-js提供的StackTrace.fromError(error)方法進(jìn)行堆棧信息追蹤
第三步
發(fā)送錯(cuò)誤日志,此處使用了ngx-logger
第四步
app.moudle.ts
{provide: ErrorHandler, useClass: GlobalErrorHandler}
測試
模擬錯(cuò)誤
errorTest = [];
let a = this.errorTest[0]['name'];
結(jié)果

image.png
下一篇開始常用插件的使用。