Search code examples
javascriptmysqlnode.jsasynchronouses6-promise

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?


Solution

  • 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.