0

I have a function like this:

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]
}

But I got an error UnhandledPromiseRejectionWarning: Error: Patient Not Found!

This happened cause I have used async function. How can I make this code running properly?

2 Answers2

1

In order to manage errors in an async function, you have to use a try/catch block:

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;
    }
    
}

I should mention, that if you simply want to throw the error thats received from getPatients theres no need for a try/catch block at all. Its only needed if you wish to modify the error or perform an extra action according to the error that was thrown.

Sagi Rika
  • 2,839
  • 1
  • 12
  • 32
0

You have 2 options: First one is try/catch block with await keyword. Please notice that await has to be used in async function.

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

Second one is catch function

getPatient(foo)
    .then(patient => {
        // handle your data here
    }).catch(error => {
        // error handling here
    });
  • In this case I want to check if patient exist in my database, I throw the Error if function return empty array. I tried for the first code but not working. – Fahri Bullseye Jul 08 '21 at 07:30