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

标签 javascript validation error-handling runtime-error throw

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

const myModule = function (value1) {

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

  // Do stuff here

}

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

/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 是在 JavaScript 中抛出错误的正确方法。但您可以使用Console内置方法,它将允许您抛出不同类型的错误。

如果您要抛出不同类型的消息/错误/异常,您可以从 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

}

关于javascript - 函数参数验证的正确错误抛出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44121426/

相关文章:

r - R glm.nb预测三个变量返回错误

用于显示验证器消息的 jquery 工具提示

angularjs - 如何防止 AngularJS 第一次验证表单控件

c# - 如何在 ASP.NET Core 中以不同方式处理(或区分)API 调用和 MVC( View )调用的错误

javascript - Material UI – 全局复选框焦点样式(不是本地)

c# - 关闭框触发非模态表单的验证

python - 无法在 Jupyter Notebook (Chrome) 中打开 PDF 文件

javascript - 我如何能够比较 JS 中的未定义?

javascript - 如何将 $stateParams 从 ui-router 传递到 resolve 服务?

javascript - 如何在 Firefox 插件中调用控制台调试面板?