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?
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.
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.
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.
Handling rejected promises You can handle rejected promises without a try block by chaining a catch() handler before awaiting the promise.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With