Home > Software engineering >  Combine throw new Error with await in one expression
Combine throw new Error with await in one expression

Time:07-15

can I throw error and use await word in one statement using AND operator, the following code explains well my request :

throw new Error() && await client.end().

This latter works fine till now, and for my question, is this the better form of writing this and will it create problems in some cases.

My main purpose is to close the Data Base connection and throw the Error.

CodePudding user response:

for such use cases I think the finally block is the right solution. See on the mozilla docs here. In your case it would be something like

try {
    // stuff that can throw an error
} catch {
    // handle the error case
} finally {
    // in any case, close the connection
    await client.end()
}

Or, if you want to keep the connection open when there's no error, just move the close line in the catch block:

try {
    // stuff that can throw an error
} catch {
    // handle the error case
    await client.end()
}
  • Related