Promise被拒绝时处理错误消息的翻译

使用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.');
  }
}

在应用程序的另一部分中,我进行函数调用以检索待办事项列表。如果待办事项失败,处理错误翻译的最佳方法是什么?

到目前为止,我提出了两个想法:

  1. 返回翻译键并在调用方法后处理翻译:
getTodos()
  .then((todos: Array<Todos>) => {
    ... 
  })
  .catch((error: string) => {
    console.log(this.$t(error.message));  // this would result in e.g. this.$t('getTodosFailed')
  });
  1. 翻译第一个函数中的错误并返回翻译后的字符串:
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');
  }
}

这些方法中的任何一种好吗?

glueyou 回答:Promise被拒绝时处理错误消息的翻译

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/2605023.html

大家都在问