Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 997
Fredo Corleone Avatar asked Jul 04 '18 14:07

Fredo Corleone


People also ask

How do you handle unhandled promise rejection?

If an error condition arises inside a promise, you “reject” the promise by calling the reject() function with an error. To handle a promise rejection, you pass a callback to the catch() function. This is a simple example, so catching the rejection is trivial.

What is unhandled promise?

The unhandledrejection event is sent to the global scope of a script when a JavaScript Promise that has no rejection handler is rejected; typically, this is the window , but may also be a Worker . This is useful for debugging and for providing fallback error handling for unexpected situations.

How do you catch uncaught in promise error?

What does that log "Uncaught (in promise)" mean? It means that there was an error in one of our promises, but we did not write any code in order to handle that error and try to catch it. The way you catch an error in a promise is you chain a . catch() to it.

How do you handle reject In await?

Handling rejected promises You can handle rejected promises without a try block by chaining a catch() handler before awaiting the promise.


1 Answers

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?

like image 137
Marcos Casagrande Avatar answered Oct 11 '22 20:10

Marcos Casagrande