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?

lowerkey
  • 8,105
  • 17
  • 68
  • 102
  • 1
    not sure, but you could catch it and rethrow it after inspecting it. – goat May 07 '12 at 17:03
  • related: [Conditional catch clauses - browsers support](https://stackoverflow.com/q/20483597/1048572) – Bergi Jun 20 '17 at 22:47

1 Answers1

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
}]
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Appreciate the MDN citation ... totally missed that part when reading the documentation, works well now. – afreeland May 29 '13 at 15:55
  • I'm sorry to ask, but does anyone know why this feature is neither standard nor being standardized ? It could be great ! – Ugo Evola Apr 29 '22 at 18:36
  • 1
    @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](https://github.com/tc39/proposal-pattern-matching#integration-with-catch). – Bergi Apr 30 '22 at 22:44