Fredo Corleone
Fredo Corleone

Reputation: 572

Try/catch block and unhandled promise exception

I wanted to test my async function querying a table which does not exist. Therefore the error is generated on purpose.

async function getPosts() {
  try {
    const connection = await dbConnection()
    const result = await connection.query('SELECT * FROM x')
    await connection.release()
    console.log(result)
  }
  catch(ex) {
     throw new Error(ex)
  } 
}

When I call that function:

UnhandledPromiseRejectionWarning: Error: Error: ER_NO_SUCH_TABLE: Table 'test.x' doesn't exist.

Can you tell me why?

Upvotes: 13

Views: 11551

Answers (2)

Fredo Corleone
Fredo Corleone

Reputation: 572

Hi myself from the past!

Your console displays an unhandled error because in your catch block you are (I was) stupidly re-throwing a JavaScript error. 🤦

Just remove that throw new Error(ex) from your catch and change it with some error handling logic instead.

Upvotes: 9

Marcos Casagrande
Marcos Casagrande

Reputation: 40444

You're getting UnhandledPromiseRejectionWarning because you're not adding a .catch handler to getPosts()


getPosts()
  .then(console.log)
  .catch(console.error); // You're missing this

Or using async/await

try {
    const posts = await getPosts();
    console.log(posts);
} catch(e) { // Missing this
    console.error(e); 
}

There is no need to add a try/catch on your getPosts function if you're going to throw the error again without any modification. Just let it bubble up, and handle the error when calling getPosts() as shown above.

async function getPosts() {

    const connection = await dbConnection()
    const result = await connection.query('SELECT * FROM x')
    await connection.release()
    return result;
}

Regarding your current error, you're trying to perform a query on a table that doesn't exist.

You can learn more about this in the following question: What is an unhandled promise rejection?

Upvotes: 16

Related Questions