Search code examples
javascriptthrow

Is there a specific error type that should be used to express an unmet requirement in javascript?


When creating a module that will be used by others, is there a standardized, specific error type that should be thrown to express an unmet requirement?

I'm a function. I need x. x is undefined and I'm upset about it. What do I throw?


Solution

  • Unlike strongly typed C-style languages such as C# and Java, JavaScript doesn't have many out-of-the-box exception types.

    try..catch is also a little-used feature of the language, so it's not overly common to see people explicitly throw in JavaScript.

    With the relatively recent introduction of promises to the language, and--in particular--async/await try..catch is becoming more common.

    As far as what errors to throw specifically, it's always up to the individual developer, and I recommend documenting what errors your API will throw. That said, there are a handful of common errors that are built into the language and have natural use cases:

    • Error - obviously this is the generic class to throw a generic error
    • RangeError - throw this if input is not in the appropriate range, such as when you expect a positive number and receive a negative.
    • ReferenceError - typically this is meant for variables that don't exist, but this can also be useful for APIs that expose data access via strings. I.E.:

      getData('foo') //ReferenceError: 'foo' does not exist in data`
      
    • TypeError - this represents an error when a value is not of the right type (this is probably the one you want). For example, you have a callback parameter that requires a function, and the user provides a string.

    There are more built-in Error types than these, but they tend to be much less common in the wild.