Why the try...catch is not working for below sample code?
const http2 = require("http2")
const url = require("url")
function sendRequest() {
return new Promise((resolve, reject) => {
var r = http2.request({
"host": "www.google.com",
"method": "GET",
"path": "/"
}, (resp) => {
var data = []
resp.on("data", (chunk) => {
throw ("Error")
})
resp.on("end", () => {
console.log("ended")
resolve("finished")
})
resp.on("error", (e) => {
console.log("error")
reject(e)
})
})
r.end()
})
}
async function wrapper(){
try {
console.log("Sending request")
await sendRequest()
console.log("Finished sending Request")
}catch(e){
console.log("error!") // Supposed to see this
console.log(e)
}
console.log("All finished") // Supposed to see this
}
wrapper()
Output is as follow:
Sending request
/Users/test-user/test.js:15
throw ("Error")
^
Error
Process finished with exit code 1
Because a node. js process can/will terminate from an unhandled promise rejection, it is advisable that you always use try/catch with await, and always add a .
If the Promise is rejected, the await expression throws the rejected value. If the value of the expression following the await operator is not a Promise , it's converted to a resolved Promise. An await splits execution flow, allowing the caller of the async function to resume execution.
If a promise resolves normally, then await promise returns the result. But in the case of a rejection, it throws the error, just as if there were a throw statement at that line. In real situations, the promise may take some time before it rejects. In that case there will be a delay before await throws an error.
You can throw
inside a promise and catch the error with catch
so long as the error is in the promise itself and not in different async callback.
For example, the test()
works as expected, but test2()
does not:
function test(){
return new Promise((resolve, reject) => {
throw (new Error("error"))
})
}
function test2(){
return new Promise((resolve, reject) => {
setTimeout(() => {
throw (new Error("error"))
}, 100)
})
}
async function go (){
try {
await test()
} catch(err){
console.log("caught error from test(): ", err.message)
}
try {
await test2()
} catch(err){
console.log("caught error from test2(): ", err.message)
}
}
go()
Both cases work fine with reject()
instead of throw()
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