Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try... Catch in async await not catching error [duplicate]

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
like image 274
MK Yung Avatar asked Nov 07 '17 17:11

MK Yung


People also ask

Should I always use try catch with async-await?

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 .

How do you handle promise rejection with await?

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.

What happens if await throws error?

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.


1 Answers

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()

like image 85
Mark Avatar answered Sep 19 '22 14:09

Mark