函数参数验证的正确错误抛出

Proper Error throwing for function argument validation

我有以下类型的函数定义:

const myModule = function (value1) {

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

  // Do stuff here

}

有一个必需的 value1 parameter/argument 需要传递到函数中。如果它丢失了,那么我需要抛出一个错误。我是否正确抛出错误?当我 运行 这个时,我在控制台中得到这种类型的输出:

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

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

这是执行此操作的正确方法吗?它将实际的 throw 语句输出到控制台似乎很奇怪。

是的,使用 throwstatement is the proper way to throw errors in JavaScript. But you can use the Console 内置方法,它允许您抛出不同类型的错误。

如果您有不同类型的 messages/errors/Exceptions 可以投掷,您可以从 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.

演示:

这是一个简单的演示,展示了这些方法的使用:

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

}