medici
medici

Reputation: 199

Handling exception properly in ionic2 app

My ionic2 app use firebase authentication. I try to handle auth/account-exists-with-different-credential error when use same email login to multiple provider(google and facebook) like this.

constructor(public af: AngularFire,public navCtrl: NavController) {
    firebase.auth().getRedirectResult()
      .then(res=>{
        console.log('success',res)
      })
  .catch((err:any)=>{
    console.log(error.message)
    if (err.code=='auth/account-exists-with-different-credential'){
       doaccountlink();
    }
  })
  }



    fblogin(){
        firebase.auth().signInWithRedirect(new firebase.auth.FacebookAuthProvider())
      }

      gglogin(){
        firebase.auth().signInWithRedirect(new firebase.auth.GoogleAuthProvider())
      }

i can catch that error code in catch block(as expect) but the problem is Exception still show in console and my page also show error(see attach image). i'm new to javascript/typescript, In java if i already catch error in catch block then it should be fine. or something wrong in my code. How can i prevent this exception to show on my page?

enter image description here

Upvotes: 3

Views: 1529

Answers (1)

sebaferreras
sebaferreras

Reputation: 44669

We would need to carefully debug your code to understand exactly what's going on, there must be another exception being thrown somewhere else and that's why you see that page; but there are a few tips that may come in handy:

  1. That page that is shown with the exception, is because of the IonicErrorHandler. You can take a look at your app.module.ts file, and in the providers array you'll find this line:

    providers: [
        // services...
        { provide: ErrorHandler, useClass: IonicErrorHandler }
    ]
    

    So basically Ionic is extending Angular 2 default's ErrorHandler with that class. Also notice that this is being done only when running on the dev server, nothing is done in production (you can take a look at the source code here).

  2. I'm not sure if this make sense in the context of your app, but you can build your own error handler, and try to handle the exceptions with your own code. Just like you can see here you can do that by creating a new class that implements the ErrorHandler

    class MyErrorHandler implements ErrorHandler {
        handleError(err: any): void {
            // do something with the error
        }
     }
    

    And then in your app.module.ts replace the

    { provide: ErrorHandler, useClass: IonicErrorHandler }

    with

    { provide: ErrorHandler, useClass: MyErrorHandler }

Upvotes: 2

Related Questions