ion-js
ion-js copied to clipboard
consider defining and throwing custom error classes
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.
What value does it add?
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).
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.
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.