2016-09-07 32 views
0

我现在有这样的代码:如何获得火力地堡异常成switch语句

if (!task.isSuccessful() && task.getException() != null) { 
    FirebaseCrash.report(task.getException()); 
    Log.w(TAG, "signInWithCredential", task.getException()); 
    Toast.makeText(SignUp.this, "Authentication failed: " + task.getException().getMessage(),Toast.LENGTH_LONG).show(); 
} 

有时候用户得到一个FirebaseAuthUserCollisionException,我要检测它在switch声明,如下所示:

switch(task.getException()){ 
    case /*I don't know what goes here*/: 
     //Whatever 
} 

但是,当你阅读,我不知道要在case声明中放什么。我在那里放什么?换句话说,FirebaseAuthUserCollisionException位于哪里以便我可以访问它? FirebaseAuthUserCollisionException只是一个类,所以我目前无法做任何事情。

+0

同样的问题是[这里讨论](http://stackoverflow.com/q/37859582/4815718)。当我看到事情时,没有简单而干净的方式去做你想做的事。除了这里回答中提供的方法之外,您还可以考虑[此解决方案](http://stackoverflow.com/a/38490022/4815718)。 –

回答

1

火力地堡认证例外全部来自FirebaseAuthException,其中有一个getErrorCode()方法获得。

所以:

if(task.getException() instanceof FirebaseAuthException){ 
    FirebaseAuthException e = (FirebaseAuthException)task.getException(); 
    switch (e.getErrorCode()) { 
     ... 
    } 
} 
+0

非常感谢,但是如何获得“FirebaseAuthUserCollisionException”? 'case“FirebaseAuthUserCollisionException”:'? –

+0

切换案例不能用Java测试类。如果你想要一个switch case,你需要和'getErrorCode()'进行比较。如果你想和班级进行比较,你需要像@rafal所说的那样嵌套if。 –

+0

好,但是我怎么比较这个班?如果那是真的,你为什么在你的答案中包含switch(e.getErrorCode())?爱你的答案btw,非常有用:) –

0

尝试:

if(task.getException() instanceof FirebaseAuthUserCollisionException){ 
    //whatever 
} 
+1

如果其他异常是此异常类的子类,则它也属于此类。 – mhenryk