Firebase 函数 如何正确处理错误



注意:这个问题主要是关于错误处理的,如果这是一个OK的方法,而不是关于嵌套承诺,请在关闭前阅读

由于Firestore和firebase数据库等服务目前没有错误代码,因此我正在使用一个系统来了解函数失败的位置并相应地处理错误,简化版本如下:

exports.doStuff = functions.https.onCall((data, context) => {
return [promise doing stuff goes here].catch(error => { throw new Error('ERROR0') })
.then(result => {
return [promise doing stuff goes here, needs result of previous promise]
.catch(error => { throw new Error('ERROR1') })
})
.then(result => {
return [promise doing stuff goes here, needs result of previous promise]
.catch(error => { throw new Error('ERROR2') })
})
.then(result => {
//inform client function successful
return {
success: true
}
})
.catch(error => {
if (error !== null) {
switch (error.message) {
case 'ERROR0':
//do stuff
throw new functions.https.HttpsError('unknown', 'ERROR0');
case 'ERROR1':
//do stuff
throw new functions.https.HttpsError('unknown', 'ERROR1');
case 'ERROR2':
//do stuff
throw new functions.https.HttpsError('unknown', 'ERROR2');
default:
console.error('uncaught error: ', error);
throw error;
}
}
});
});

问题是,对于每个返回的承诺中的每个.catch(),我都会收到以下警告:warning Avoid nesting promises

所以我的问题是,有没有更好的方法来处理错误?

归根结底,这是一种风格建议,以防止奇怪和难以识别的错误。大多数情况下,重写可以消除警告。例如,您可以按如下方式重写代码,同时保留相同的功能。

exports.doStuff = functions.https.onCall(async (data, context) => {
const result1 = await [promise doing stuff goes here]
.catch(error => {
throw new functions.https.HttpsError('unknown', 'ERROR0', { message: error.message } )
});
const result2 = await [promise based on result1 goes here]
.catch(error => {
throw new functions.https.HttpsError('unknown', 'ERROR1', { message: error.message } )
});
const result3 = await [promise based on result1/result2 goes here]
.catch(error => {
throw new functions.https.HttpsError('unknown', 'ERROR2', { message: error.message } )
});
return {
success: true
};
});

最后,与其在任何地方都使用unknown,不如对第一个参数使用几个可能的值之一,同时将所需的任何支持信息作为第三个参数传递(如上所示,我传递原始错误消息(。

最新更新