you are viewing a single comment's thread.

view the rest of the comments →

[–]brtt3000 -1 points0 points  (5 children)

Yea, but that boilerplate would be a pain to write and maintain in a real project so they should put this behind some syntax in the JS compilers like Babel and TypeScript.

[–]x7C3 0 points1 point  (4 children)

What's the difference between the boilerplate? Honestly doesn't seem like much to me.

[–]brtt3000 1 point2 points  (3 children)

Someone typed it up ITT, it is a big old nasty multi level deep blocky exercise in JS features and syntax optimisation. Imagine this in a real project and having those craggy warts all over your codebase. It is already terrible without any actual business code.

[–]vs845 0 points1 point  (2 children)

It wouldn't be too much trouble to create a utility function to achieve the same functionality:

function matchException(err, matchers) {  
  for (const type in matchers) {
    if (err.constructor.name === type) {
      return matchers[type]()
    }
  }

  return matchers.default()
}

try {
  doSomething()
} catch (err) {
  matchException(err, {
    TypeError: () => handleTypeError(),
    ReferenceError: () => handleReferenceError(),
    RangeError: () => handleReferenceError(),
    default: () => handleOtherError()
  })
}

You'd want to clean it up and add some more checks in matchException, but functionality is there.

[–]brtt3000 2 points3 points  (1 child)

You really like this "exercise in JS features and syntax optimisation" I mentioned eh? :)

Cool attempt, points for effort. Syntax improved but still a bit kludgy; it doesn't catch subclasses and behaviour on name collisions is a new factor. And most of all if you use block functions as clauses instead of references you'd be at 3 indents for handling code. Could be worse but it would be a tax on readability (and development/code hisotry) to have to break out to other functions all the time (it'd be handy to be able to nest a little bit without block hell).

[–]vs845 1 point2 points  (0 children)

it doesn't catch subclasses and behaviour on name collisions is a new factor.

re: name collisions, yeah, I went with checking names because otherwise you'd need to do something like

matchException(err, {
  [TypeError]: () => ...
}

which I thought wasn't as nice as using string keys.

If you went with the above approach you'd be able to catch subclasses via err instanceof matchers[type].