使用Promises进行API调用时,如何处理错误消息的翻译?我的应用程序中包含以下代码(该应用程序使用i18n转换模块):
async function getTodos (): Promise<Array<Todo>> {
try {
const todos = await axios.get(`...endpointUrl/todo/list`);
return todos.data;
} catch {
throw new Error('Getting todos failed.');
}
}
在应用程序的另一部分中,我进行函数调用以检索待办事项列表。如果待办事项失败,处理错误翻译的最佳方法是什么?
到目前为止,我提出了两个想法:
- 返回翻译键并在调用方法后处理翻译:
getTodos()
.then((todos: Array<Todos>) => {
...
})
.catch((error: string) => {
console.log(this.$t(error.message)); // this would result in e.g. this.$t('getTodosFailed')
});
- 翻译第一个函数中的错误并返回翻译后的字符串:
async function getTodos (): Promise<Array<Todo>> {
try {
const todos = await axios.get(`...endpointUrl/todo/list`);
return todos.data;
} catch {
throw new Error(this.$t('getTodosFailed');
}
}
这些方法中的任何一种好吗?