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?

4
  • How is PatientDAO.getPatients implemented? Commented Jul 8, 2021 at 7:01
  • Does this answer your question? How to properly implement error handling in async/await case Commented Jul 8, 2021 at 7:02
  • @ManuelSpigolon just for getting data from server using fetch Commented Jul 8, 2021 at 7:27
  • @roy for my case, PatientDAO not trowed any error, I was used custom error if the function return empty array Commented Jul 8, 2021 at 7:36

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It's just return null
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
    });

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.