1. 程式人生 > >ionic 調用restful API services時全局錯誤處理的實現 或自定義錯誤處理的實現

ionic 調用restful API services時全局錯誤處理的實現 或自定義錯誤處理的實現

ner images AS tor framework ets inject sta port

往往我們的ionic程序需要調用API Service. 比如天氣,地圖等等。當這些API Service 不穩定或者不可訪問時,我們可以通過在註冊一個自定義的ErrorHandler, 來處理此類錯誤。

1. 將自定義錯誤處理類作為provider, 也就是Service. 在終端使用命令: ionic g provider GlobalErrorHandler . ionic generate 命令行定義可以參考此處

2. 實現GlobalErrorHandler, 完整代碼如下。

import { ErrorHandler, Injectable } from ‘@angular/core‘;

import { AlertController } from ‘ionic-angular‘;

@Injectable()

export class GlobalErrorHandler extends ErrorHandler {

constructor(public alertCtrl: AlertController) {

super();

}

handleError(error: any): void {

super.handleError(error);

// IMPORTANT: Rethrow the error otherwise it gets swallowed

if (error) {

if (error.status === 0 && error.name === ‘HttpErrorResponse‘ && error.statusText === ‘Unknown Error‘) {

this.showAlert(‘ 後臺服務遇到了問題,目前正在修復中,請稍後訪問,給您帶來不便,深表歉意。‘);

//It‘s better to add this to log file.

}

}

}

showAlert(subTitleText) {

let alert = this.alertCtrl.create({

title: ‘發生錯誤!‘,

subTitle: subTitleText,

buttons: [‘確定‘]

});

alert.present();

}

}

3. 在 \src\app\app.module.ts 中註冊 GlobalErrorHandler . 以下是代碼片段, 請關註粗體部分。

import { GlobalErrorHandler } from ‘../providers/global-error-handler/global-error-handler‘;

@NgModule({

declarations: [...],

imports: [...],

bootstrap: [IonicApp],

entryComponents: [

MyApp

],

providers: [

{provide: ErrorHandler, useClass: GlobalErrorHandler},

// IMP. GlobalErrorHandler should be here, otherwise it would not be triggered.

GlobalErrorHandler

]

})

export class AppModule {}

這樣的話,我們就在ionic程序中引入了全局錯誤處理。 一旦第三方的services 或者我們自己的service 發生錯誤不可訪問時, 頁面將會有Alert彈出。 如下圖所示。

技術分享圖片

ionic 調用restful API services時全局錯誤處理的實現 或自定義錯誤處理的實現