Often our ionic program needs to invoke the API Service. such as weather, maps and so on. When these API Service is unstable or inaccessible, we can handle such errors by registering a custom ErrorHandler. 1. Use the custom error-handling class as the provider, which is the service. In terminal use command: Ionic g provider Globalerrorhandler. The ionic generate command line definition can be referenced here in 2. Implement Globalerrorhandler, complete code as follows.
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 (' Background service encountered a problem, is currently being repaired, please visit later, to bring you inconvenience, apologize. ‘);
It ' s better to add the this to log file.
}
}
}
Showalert (Subtitletext) {
Let alert = This.alertCtrl.create ({
Title: ' An error has occurred! ‘,
Subtitle:subtitletext,
Buttons: [' OK ']
});
Alert.present ();
}
}
3. Register the Globalerrorhandler in the \src\app\app.module.ts. Here's the code snippet, follow the bold section.
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 is here, otherwise it would isn't be triggered.
Globalerrorhandler
]
})
Export class Appmodule {}
In this case, we have introduced global error handling in the Ionic program. The page will have alert popup once the third party services or our own service has been incorrectly inaccessible. As shown in.
Ionic implementation of global error handling when invoking RESTful API services or implementation of custom error handling