Comment

Comment by benjoffe

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.

parent benjoffe 10 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton