Search code examples
javascriptvalidationerror-handlingruntime-errorthrow

Proper Error throwing for function argument validation


I have the following type of function definition:

const myModule = function (value1) {

  // Is value1 missing?
  if (typeof(value1) === 'undefined') {
    throw new Error('value1 is missing')
  }

  // Do stuff here

}

There is a required value1 parameter/argument that needs to be passed into the function. If it's missing, then I need to throw an error. Am I throwing the error correctly? When I run this, I get this type of output in the console:

/Users/me/script.js:10
    throw new Error('value1 is missing')
    ^

Error: value1 is missing
    at new myModule (/Users/me/script.js:10:11)

Is this the proper way to do this? It seems weird that it outputs the actual throw statement into the console.


Solution

  • Yes using the throwstatement is the proper way to throw errors in JavaScript. But you can use the Console built-in methods, it will allow you to throw different types of errors.

    If you have different types of messages/errors/Exceptions to throw you can profit from the Console methods:

    Console.error()

    Outputs an error message. You may use string substitution and additional arguments with this method.

    Console.info()

    Informative logging information. You may use string substitution and additional arguments with this method.

    Console.log()

    For general output of logging information. You may use string substitution and additional arguments with this method.

    Console.trace()

    Outputs a stack trace warning message. You may use string substitution and additional arguments with this method.

    Console.warn()

    Outputs a warning message. You may use string substitution and additional arguments with this method.

    Demo:

    This is a simple Demo showing the use of these methods:

    const myModule = function(value1) {
    
      // Is value1 missing?
      if (!value1) {
        console.error('value1 is missing!!!');
      //Is value a string?
      } else if (typeof value !== "string") {
        console.warn('value1 must be a string!!!');
      }
      // Do stuff here
    
    }