如何处理异步/等待函数中的错误?

时间:2021-07-08 06:59:25

标签: node.js

我有一个这样的功能:

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 函数。我怎样才能让这段代码正常运行?

2 个答案:

答案 0 :(得分:0)

为了管理 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 块。仅当您希望根据抛出的错误修改错误或执行额外操作时才需要它。

答案 1 :(得分:0)

您有两个选择: 第一个是带有 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
    });