【问题标题】:How to handle error in async/await function?如何处理异步/等待函数中的错误?
【发布时间】:2021-09-18 15:27:53
【问题描述】:

我有这样的功能:

async getPatient(patientId: string): Promise<PatientDTO> {
    const patient = await PatientDAO.getPatients({ id: patientId })

    if (patient.length === 0) {
        throw new NotFoundError("Patient Not Found!")
    }

    return patient[0]
}

但是我遇到了一个错误 UnhandledPromiseRejectionWarning: Error: Patient Not Found!

这是因为我使用了async 函数。如何让这段代码正常运行?

【问题讨论】:

  • PatientDAO.getPatients是如何实现的?
  • @ManuelSpigolon 仅用于使用 fetch 从服务器获取数据
  • @roy 就我而言,PatientDAO 没有出现任何错误,如果函数返回空数组,我会使用自定义错误

标签: node.js


【解决方案1】:

为了管理async 函数中的错误,您必须使用try/catch 块:

async getPatient(patientId: string): Promise<PatientDTO> {
    try {
      const patient = await PatientDAO.getPatients({ id: patientId })

      return patient[0]
    } catch (error) {
        // Do whatever you may want with error
        throw error;
    }
    
}

我应该提到,如果您只是想抛出从getPatients 收到的错误,则根本不需要try/catch 块。仅当您希望根据抛出的错误修改错误或执行额外操作时才需要它。

【讨论】:

  • 只是返回null
【解决方案2】:

您有两个选择: 第一个是带有await 关键字的try/catch 块。请注意await 必须在async 函数中使用。

try {
    const patient = await getPatient(foo);
    // handle your data here
} catch(e) {
    // error handling here
}

第二个是catch函数

getPatient(foo)
    .then(patient => {
        // handle your data here
    }).catch(error => {
        // error handling here
    });

【讨论】:

  • 在这种情况下,我想检查我的数据库中是否存在患者,如果函数返回空数组,我会抛出错误。我尝试了第一个代码但没有工作。
猜你喜欢
  • 2018-07-29
  • 2020-06-29
  • 2020-12-19
  • 1970-01-01
  • 2021-09-23
  • 2022-01-09
  • 2018-04-06
  • 2018-11-12
  • 1970-01-01
相关资源
最近更新 更多