16

I read about try catch(e if e instanceof ...) blocks on MDN, however, upon trying it in Node.js, I get a SyntaxError: Unexpected token if.

If this doesn't work, is there another way to catch specific exceptions, instead of everything that might occur?

2
  • 1
    not sure, but you could catch it and rethrow it after inspecting it. Commented May 7, 2012 at 17:03
  • related: Conditional catch clauses - browsers support Commented Jun 20, 2017 at 22:47

1 Answer 1

17

To cite the MDN doc you linked to:

Note: This functionality is not part of the ECMAScript specification.

and

JavaScript 1.5, NES 6.0: Added multiple catch clauses (Netscape extension).

so: No, this won't be possible in Node.js. Yet, of course you can use the following syntax as a workaround:

try {
    try_statements
} catch (e) {
    if (e instanceof ...)
        catch_statements_1
    else if (e instanceof ...)
        catch_statements_2
    else
        throw e;
} [finally {
    finally_statements
}]
Sign up to request clarification or add additional context in comments.

3 Comments

Appreciate the MDN citation ... totally missed that part when reading the documentation, works well now.
I'm sorry to ask, but does anyone know why this feature is neither standard nor being standardized ? It could be great !
@UgoEvola It didn't make it into ES5, and interest since then has waned, probably because it's so easy to workaround with a little boilerplate. The pattern matching proposal explores new ways to do this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.