ion-js icon indicating copy to clipboard operation
ion-js copied to clipboard

consider defining and throwing custom error classes

Open pbcornell opened this issue 5 years ago • 4 comments

JavaScript tradition seems to be throw Error, but perhaps JavaScript/TypeScript provides some capabilities for defining custom error classes. Let's evaluate whether we should throw custom error classes for various error conditions in the API.

pbcornell avatar Aug 13 '19 15:08 pbcornell

What value does it add?

wesboyt avatar Aug 13 '19 17:08 wesboyt

A few thoughts:

  • a well-named error class provides a little more information to the receiver
  • in cases where a method's implementation might have multiple error conditions, throwing a different error class for different types of errors allows the caller to handle the errors differently (by defining a catch block per error)
  • per the reviewer's comment in #291, catching Error doesn't allow the test code to assert whether the method is throwing for the expected reason, so we're not fully verifying the contract of the methods

And while it's possible to achieve similar results by inspecting an error's message, that tends to be a brittle approach (e.g., if we change an error message's spelling/punctuation/whatever, calling code may break).

pbcornell avatar Aug 13 '19 17:08 pbcornell

In typescript theres little difference between a checking a error's "class" and checking an errors string message. instance of is just checking a string in an object's prototype vs checking the string msg.

Not sure i agree with the first point.

wesboyt avatar Aug 13 '19 18:08 wesboyt

per @almann in #307:

We really should consider having some first-class error type like IonError and have it prototype extend Error. Since we're targeting ES6, this is pretty straightforward, e.g.:

class IonError extends Error {
  constructor(...args) {
    super(...args);
  }
}

These errors should be explicit, and we should support forms that allow for properties like lineNumber and columnNumber or the like.

pbcornell avatar Sep 16 '19 17:09 pbcornell