由于当前没有诸如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()
返回的promise中的每个消息,我都会收到以下警告: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
您可以在第一个参数中使用几个可能的值中的一个,而不用随处使用,同时将您需要的任何支持信息作为第三个参数传递(如上图所示,其中显示了原始错误消息)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句