ionic4-GlobalErrorHandler(全局異常捕捉與處理)

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

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容