如果Firestore查询任务失败(task.isSuccessful()返回false),我可以期望task.getException()返回非null值

时间:2019-03-24 07:55:45

标签: android firebase google-cloud-firestore

我正在Android应用程序中使用Firestore。

在以下代码中,我可以期望异常为非null吗?

FirebaseFirestore.getInstance().collection("items").document("abc").get().addOnCompleteListener(task -> {
    if (!task.isSuccessful()) {
        Exception e = task.getException();
        //Can I expect e to be non null, or do I have to check for null?
    }
});

2 个答案:

答案 0 :(得分:1)

通过OnComplete方法中的task文档,是的,它不能为null。

返回导致任务失败的异常。如果Task尚未完成或已成功完成,则返回null。链接-https://developers.google.com/android/reference/com/google/android/gms/tasks/Task.html#getException()

答案 1 :(得分:1)

如果使用OnCompleteListener,则可以保证结果或异常。如果为task.isSuccessful(),则可以确保您有一个结果对象,并且没有例外。

addOnCompleteListener(task -> {
    if (!task.isSuccessful()) {
        // Exception is guaranteed to be non-null
        Exception e = task.getException();
    }
    else {
        // Result is guaranteed to be non-null
        task.getResult();
    }
});

如果使用OnSuccessListener,则保证结果为非null,但是如果出现错误,则不会调用该结果。

如果使用OnFailureListener,则保证该异常为非null,但如果没有错误,则不会调用该异常。

如果您不想在OnSuccessListener内检查是否成功,则可以将OnFailureListenerOnCompleteListener链接起来。

您可以在{{3}}中阅读有关任务的规范参考。