英文:
firestore error handling for insert, update, delete
问题
获取数据时的错误处理:
对于单个文档:
const user = await firebase.firestore().collection('users').doc('123').get()
if (!user.exists) {
throw new Error("获取失败")
}
对于多个文档:
const { docs } = await firebase.firestore().collection('users').get()
if (docs?.length < 1) {
throw new Error("未找到数据")
}
处理错误的逻辑是否应该如下:
const res = firebase.firestore().collection('users').doc().set({ name: 'Ben' })
if (!res) {
throw new Error("插入失败")
}
...
const res = firebase.firestore().collection('users').doc('123').update({ name: 'Ben' })
if (!res) {
throw new Error("更新失败")
}
...
const res = firebase.firestore().collection('users').doc('123').delete()
if (!res) {
throw new Error("删除失败")
}
英文:
For get(), this is how I handle error:
for single doc:
const user = await firebase.firestore().collection('users').doc('123').get()
if(!user.exist){
throw new Error("get failed")
}
for multiple docs:
const {docs} = await firebase.firestore().collection('users').get()
if(docs?.length < 1){
throw new Error("no data found")
}
Should I handle errors like the logic below?
const res = firebase.firestore().collection('users').doc().set({name: 'Ben'})
if(!res){
throw new Error("insert failed")
}
...
const res = firebase.firestore().collection('users').doc('123').update({name: 'Ben'})
if(!res){
throw new Error("update failed")
}
...
const res = firebase.firestore().collection('users').doc('123').delete()
if(!res){
throw new Error("delete failed")
}
答案1
得分: 0
可以使用 try catch
,需要在异步块中执行,就像这样:
async function sample() {
try {
const res = await firebase.firestore().collection('users').doc().set({
name: 'Ben'
});
} catch (error) {
console.error('Error inserting document:', error);
// 处理错误或抛出带有自定义消息的新错误
}
}
或者,如果你想立即捕获错误,可以使用以下方法,附加 .catch()
方法:
async function sample() {
const res = await firebase.firestore().collection('users').doc().set({
name: 'Ben'
}).catch(error => console.log(error));
}
看起来你正在使用 firebase V8 版本。通过升级到 firebase 模块化 SDK v9,可以轻松解决这个问题。
英文:
You can use try catch
which will need to be executed in async block like this:
async function sample() {
try {
const res = await firebase.firestore().collection('users').doc().set({
name: 'Ben'
});
} catch (error) {
console.error('Error inserting document:', error);
// handle the error or throw a new error with a custom message
}
}
Or If you want to catch the error immediately then you can use the following by appending the .catch()
method:
async function sample() {
const res = await firebase.firestore().collection('users').doc().set({
name: 'Ben'
}).catch(error => console.log(error));
}
And it seems like you are using the firebase V8 version. This can be solved easily by upgrading to firebase modular SDK v9.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论