【问题标题】:Handling exception properly in ionic2 app在 ionic2 应用程序中正确处理异常
【发布时间】:2017-05-10 10:57:50
【问题描述】:

我的 ionic2 应用使用 firebase 身份验证。当使用相同的电子邮件登录多个提供商(google 和 facebook)时,我尝试处理 auth/account-exists-with-different-credential 错误。

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())
      }

我可以在 catch 块中捕获该错误代码(如预期的那样),但问题是异常仍然显示在控制台中,我的页面也显示错误(见附件图片)。我是 javascript/typescript 的新手,在 java 中,如果我已经在 catch 块中捕获了错误,那么它应该没问题。或者我的代码有问题。如何防止此异常显示在我的页面上?

【问题讨论】:

    标签: angular typescript firebase ionic2 firebase-authentication


    【解决方案1】:

    我们需要仔细调试您的代码以准确了解发生了什么,必须在其他地方抛出另一个异常,这就是您看到该页面的原因;但有一些提示可能会派上用场:

    1. 显示异常的页面是因为IonicErrorHandler。您可以查看您的 app.module.ts 文件,在 providers 数组中您会找到这一行:

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

      所以基本上 Ionic 是用那个类扩展Angular 2 default's ErrorHandler。另请注意,仅在开发服务器上运行时才进行此操作,在生产环境中什么也不做(您可以查看源代码 here)。

    2. 我不确定这在您的应用上下文中是否有意义,但您可以构建自己的错误处理程序,并尝试使用自己的代码处理异常。就像您可以看到 here 一样,您可以通过创建一个实现 ErrorHandler 的新类来做到这一点

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

      然后在你的app.module.ts 替换

      { provide: ErrorHandler, useClass: IonicErrorHandler }

      { provide: ErrorHandler, useClass: MyErrorHandler }

    【讨论】:

    • 谢谢,sebaferreras。使用自定义错误处理程序帮助我避免在页面上显示错误,只在控制台上显示。但我认为错误应该在捕获框中处理和完成。它不应该转到 IonicErrorHandler 或 myCustomHandler。要重现该问题,只需创建空白 ionic2 项目,添加 angularfire2 模块,然后在 home.ts 中编写 2 个函数(gglogin 和 fblogin)。我在这里没有提供的是 app.module.ts 中的 firebase 配置
    • @user1084081 这可能是一个错误吗? github.com/angular/angularfire2/issues/…
    猜你喜欢
    • 1970-01-01
    • 2011-09-05
    • 2018-05-20
    • 2013-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多