Android-如何在用户级别处理Firestore异常? [英] Android - How to handle Firestore exceptions at user level?

查看:37
本文介绍了Android-如何在用户级别处理Firestore异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用程序中使用Firestore,但我不知道如何在用户级别处理由此引发的异常.(我的意思是发生此类异常时向用户显示的内容.)

I'm using Firestore in my app and I can't figure out how to handle at user level the exceptions thrown by that. (I mean what to display to the user when such exceptions occur).

例如,要在Firestore上执行任何 CRUD 操作(

For example, to perform any CRUD operation on Firestore (DocumentReference#get, DocumentReference#set, DocumentReference#update) a Task is returned, which might contain an exception, but in the documentation I can't find why this exception might be thrown by Firestore.

除了简单地记录异常并显示诸如发生错误,请稍后再试"之类的通用消息外,我们还有其他更好的方法吗?

Is there something better that we can do, rather than simply log the exception and show a generic message like "an error occurred, please try again later"?

推荐答案

与有关

As in the official documentation regarding getting data, you can get the exception from the task object like this:

docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            DocumentSnapshot document = task.getResult();
            if (document.exists()) {
                Log.d(TAG, "DocumentSnapshot data: " + document.getData());
            } else {
                Log.d(TAG, "No such document");
            }
        } else {
            //Log the error if the task is not successful
            Log.d(TAG, "get failed with ", task.getException());
        }
    }
});

请记住,当任务所代表的工作完成时,任务是 complete ,而不管其成功 failure 如何.可能有也可能没有错误,您必须检查一下.从另一方面讲,当任务所代表的工作按预期完成且没有错误时,任务是成功的".

And remember, a Task is complete when the work represented by the Task is finished, regardless of its success or failure. There may or may not have been an error, and you have to check for that. On the orter side, a Task is "successful" when the work represented by the task is finished, as expected, with no errors.

正如@Raj在他的回答中提到的那样,您也可以使用 addOnFailureListener ,但请注意,如果网络连接丢失(用户设备上没有网络连接),则 onSuccess都不会() onFailure()也被触发.这种行为是有道理的,因为仅当在Firebase服务器上已提交(或拒绝)数据后才认为任务已完成.仅当Task完成时,才会调用 onComplete(Task< T>任务)方法.因此,如果没有互联网连接,则不会触发 onComplete .

As @Raj mentioned in his answer, you can also use addOnFailureListener but note, if there is a loss of network connectivity (there is no network connection on user device), neither onSuccess() nor onFailure() are triggered. This behavior makes sense, since the task is only considered completed when the data has been committed (or rejected) on the Firebase server. onComplete(Task<T> task) method is called also only when the Task completes. So in case of no internet connection, neither onComplete is triggered.

这篇关于Android-如何在用户级别处理Firestore异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆