ionic 调用restful API services时全局错误处理的实现 或自定义错误处理的实现
2021-04-02 12:26
                         标签:alert   https   自定义   错误   终端   amp   地图   技术   otherwise     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时全局错误处理的实现 或自定义错误处理的实现 标签:alert   https   自定义   错误   终端   amp   地图   技术   otherwise    原文地址:https://www.cnblogs.com/caiyaming/p/9219126.html往往我们的ionic程序需要调用API Service. 比如天气,地图等等。当这些API Service 不稳定或者不可访问时,我们可以通过在注册一个自定义的ErrorHandler, 来处理此类错误。
 
1.   将自定义错误处理类作为provider,  也就是Service.   在终端使用命令: ionic g provider GlobalErrorHandler .  ionic generate 命令行定义可以参考此处
2.     实现GlobalErrorHandler, 完整代码如下。

文章标题:ionic 调用restful API services时全局错误处理的实现 或自定义错误处理的实现
文章链接:http://soscw.com/index.php/essay/71376.html