4 ms·
He uses the following example for when to throw your own errors: var Controller = { addClass: function(element, className) { if (!element) {
by benjoffe 10y ago
He uses the following example for when to throw your own errors:
var Controller = {
addClass: function(element, className) {
if (!element) {
throw new Error("addClass: 1st argument missing.");
}
element.className += " " + className;
}
};
I don't think this is a very good as a native error will have all this information already in a stacktrace, and if you're running Chrome dev tools with 'Pause on exceptions' then you'll be shown the exact place this fails. Additionally, you need to now keep the function name in sync with the string (your IDE / build tool will not tell you if they get out of sync).
Better cases for custom errors are situations where a native error will not be thrown, such as:
- in his example method: if className is undefined
- valid objects in a state you don't expect
- switch statements that don't match any expected case
- etc.
- blubbi2 10y agoProbably easier to just use an assertion library here. E.g. assert.ok(element)
- woah 10y agoEven easier- typescript or flow
- Touche 10y agoAdding a build step adds complexity.
- malcolmgreaves 10y agoNo. Using a weak, dynamically typed language adds complexity. Using a compiler isn't adding complexity.
- ben_jones 10y agoExcept the transpiled code is still dynamically typed. People act like when they started writing Typescript they stopped writing bugs..
- yawaramin 10y agoFirst, they don't act like that, and if they do that's dumb. Second, how is that different from writing in a statically-typed language like Haskell/Rust/what have you and then compiling down to assembly which is for all intents and purposes dynamically typed? We do it hoping to gain safety from the typing, but do we lose the type safety in the machine code? (We don't, the type-safe language rules out compiling to certain classes of erroneous code.)
- gcanti 10y agoI wrote a library [1] and a babel plugin [2] (bonus point: is Flow compatible) in order to deal with those cumbersome runtime type checks. [1] https://github.com/gcanti/tcomb https://github.com/gcanti/tcomb [2] https://github.com/gcanti/babel-plugin-tcomb https://github.com/gcanti/babel-plugin-tcomb
- philbo 10y agoHeh, me too: https://github.com/philbooth/check-types.js https://github.com/philbooth/check-types.js