[英]Code runs after catch statement catches and error and returns in react native firebase
I am having issue whenever I catch an error and return from a function, by code after the catch block still runs.每当我发现错误并从 function 返回时,我都会遇到问题,在 catch 块仍然运行之后通过代码。 Here is my two functions that I use:
这是我使用的两个函数:
usernameTaken: async (username) => {
const user = await firebase.firestore().collection("uniqueUsers").doc(username).get();
if (user.exists) {
alert("Username is taken. Try again with another username.");
throw new Error('Username is taken. Try again with another username.');
}
},
changeUsername: async (currentUsername, newUsername) => {
try {
var user = Firebase.getCurrentUser();
Firebase.usernameTaken(newUsername);
} catch (err) {
alert(err.message);
return;
}
await db.collection('uniqueUsers').doc(currentUsername).delete();
await db.collection("users").doc(user.uid).update({username: newUsername});
await db.collection("uniqueUsers").doc(newUsername).set({username: newUsername});
alert("Congratulations! You have successfully updated your username.");
}
I would greatly appreciate any help for this problem, as I have been struggling with it for over 2 days now and can't seem to find a solution.对于这个问题,我将不胜感激,因为我已经为此苦苦挣扎了 2 多天,但似乎找不到解决方案。
Try this check if your values are empty or not defined throw some error in try block eg试试这个检查你的值是否为空或未定义在 try 块中抛出一些错误,例如
cosnt user = Firebase.getCurrentUser();
const name = Firebase.usernameTaken(newUsername);
// throwing error
if(name == "") throw "is empty";
await db.collection('uniqueUsers').doc(currentUsername).delete();
In your original code, the usernameTaken()
promise is floating, because you didn't use await
.在您的原始代码中,
usernameTaken()
promise 是浮动的,因为您没有使用await
。 Because it was floating, your catch()
handler will never catch it's error.因为它是浮动的,所以你的
catch()
处理程序永远不会捕获它的错误。
changeUsername: async (currentUsername, newUsername) => {
try {
const user = Firebase.getCurrentUser();
/* here -> */ await Firebase.usernameTaken(newUsername);
} catch (err) {
alert(err.message);
return;
}
/* ... other stuff ... */
}
usernameTaken
should return a boolean usernameTaken
应该返回一个 boolean You should change usernameTaken
to return a boolean.您应该更改
usernameTaken
以返回 boolean。 This is arguably better rather than using alert()
(which blocks execution of your code) or throwing an error.这可以说比使用
alert()
(阻止代码执行)或抛出错误更好。
usernameTaken: async (username) => {
const usernameDoc = await firebase.firestore().collection("uniqueUsers").doc(username).get();
return usernameDoc.exists; // return a boolean whether the doc exists
}
Based on your current code, you have no protections for someone coming along and just deleting any usernames in your database or claiming a username that was taken between the time you last checked it's availability and when you call set()
for the new username.根据您当前的代码,您无法保护有人出现并删除数据库中的任何用户名或声明在您上次检查其可用性与您为新用户名调用
set()
之间使用的用户名。 You should secure your database so that a user can only write to a username they own.您应该保护您的数据库,以便用户只能写入他们拥有的用户名。
Add the owner's ID to the document:将所有者的 ID 添加到文档中:
"/uniqueUsers/{username}": {
username: "username",
uid: "someUserId"
}
This then allows you to lock edits/deletions to the user who owns that username.然后,这允许您将编辑/删除锁定到拥有该用户名的用户。
service cloud.firestore {
match /databases/{database}/documents {
match /uniqueUsers/{username} {
// new docs must have { username: username, uid: currentUser.uid }
allow create: if request.auth != null
&& request.resource.data.username == username
&& request.resource.data.uid == request.auth.uid
&& request.resource.data.keys().hasOnly(["uid", "username"]);
// any logged in user can get this doc
allow read: if request.auth != null;
// only the linked user can delete this doc
allow delete: if request.auth != null
&& request.auth.uid == resource.data.uid;
// only the linked user can edit this doc, as long as username and uid are the same
allow update: if request.auth != null
&& request.auth.uid == resource.data.uid
&& request.resource.data.diff(resource.data).unchangedKeys().hasAll(["uid", "username"]) // make sure username and uid are unchanged
&& request.resource.data.diff(resource.data).changedKeys().size() == 0; // make sure no other data is added
}
}
}
You are modifying your database in a way that could corrupt it.您正在以可能损坏数据库的方式修改数据库。 You could delete the old username, then fail to update your current username which would mean that you never link your new username.
您可以删除旧用户名,然后无法更新您当前的用户名,这意味着您永远不会链接您的新用户名。 To fix this, you should use a batched write to apply all these changes together.
要解决此问题,您应该使用批量写入将所有这些更改一起应用。 If any one were to fail, nothing is changed.
如果任何一个人失败了,什么都不会改变。
await db.collection("uniqueUsers").doc(currentUsername).delete();
await db.collection("users").doc(user.uid).update({username: newUsername});
await db.collection("uniqueUsers").doc(newUsername).set({username: newUsername});
becomes变成
const db = firebase.firestore();
const batch = db.batch();
batch.delete(db.collection("uniqueUsers").doc(currentUsername));
batch.update(db.collection("users").doc(user.uid), { username: newUsername });
batch.set(db.collection("uniqueUsers").doc(newUsername), { username: newUsername });
await batch.commit();
Your current usernames are case-sensitive which is not recommended if you expect your users to type/write out their profile's URL.您当前的用户名区分大小写,如果您希望您的用户键入/写出他们的个人资料的 URL,则不建议这样做。 Consider how
"example.com/MYUSERNAME"
, "example.com/myUsername"
and "example.com/myusername"
would all be different users.考虑如何
"example.com/MYUSERNAME"
、 "example.com/myUsername"
和"example.com/myusername"
都是不同的用户。 If someone scribbled out their username on a piece of paper, you'd want all of those to go to the same user's profile.如果有人在一张纸上潦草地写下他们的用户名,你会希望所有这些 go 到同一个用户的个人资料。
usernameTaken: async (username) => {
const usernameDoc = await firebase.firestore().collection("uniqueUsers").doc(username.toLowerCase()).get();
return usernameDoc.exists; // return a boolean whether the doc exists
},
changeUsername: async (currentUsername, newUsername) => {
const lowerCurrentUsername = currentUsername.toLowerCase();
const lowerNewUsername = newUsername.toLowerCase();
/* ... */
return lowerNewUsername; // return the new username to show success
}
Combining this all together, gives:将这一切结合在一起,给出:
usernameTaken: async (username) => {
const usernameDoc = await firebase.firestore().collection("uniqueUsers").doc(username).get();
return usernameDoc.exists; // return a boolean
},
changeUsername: async (currentUsername, newUsername) => {
const user = Firebase.getCurrentUser();
if (user === null) {
throw new Error("You must be signed in first!");
}
const taken = await Firebase.usernameTaken(newUsername);
if (taken) {
throw new Error("Sorry, that username is taken.");
}
const lowerCurrentUsername = currentUsername.toLowerCase();
const lowerNewUsername = newUsername.toLowerCase();
const db = firebase.firestore();
const batch = db.batch();
batch.delete(db.collection("uniqueUsers").doc(lowerCurrentUsername));
batch.update(db.collection("users").doc(user.uid), {
username: lowerNewUsername
});
batch.set(db.collection("uniqueUsers").doc(lowerNewUsername), {
username: lowerNewUsername,
uid: user.uid
});
await batch.commit();
return lowerNewUsername;
}
// elsewhere in your code
changeUsername("olduser", "newuser")
.then(
(username) => {
alert("Your username was successfully changed to @" + username + "!");
},
(error) => {
console.error(error);
alert("We couldn't update your username!");
}
);
Note: If you are using all of the above recommendations (like the security rules), one of the expected ways batch.commit()
will fail is if someone takes the username before the current user.注意:如果您使用上述所有建议(如安全规则),
batch.commit()
失败的预期方式之一是如果有人在当前用户之前使用用户名。 If you get a permissions error, assume that someone took the username before you.如果您收到权限错误,请假设有人在您之前使用了用户名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.