【问题标题】:How to fail if missing a function parameter如果缺少函数参数如何失败
【发布时间】:2021-12-17 10:00:18
【问题描述】:

在制作函数时,我检查是否填写了所需的参数,如下所示。

问题

这并不是一个真正的好方法,因为它所做的只是为缺少的参数分配一个默认值。我宁愿让执行停止并告诉我哪个函数缺少参数。如果可能,如何做到这一点?

func({
  system: "test1",
  type: "test2",
  summary: "test3",
  description: "test4",
});

function func (c) {
  c = c || {};
  c.system = c.system || "Missing system";
  c.type = c.type || 'Missing type';
  c.summary = c.summary || 'Missing summary';
  c.description = c.description || 'Missing description';

  console.log(c);
  console.log(c.system);
  console.log(c.type);
  console.log(c.summary);
  console.log(c.description);
};

【问题讨论】:

  • 抛出异常?这种方法对您来说有什么问题吗?
  • 这种方法有什么问题? 这确实不是一个好方法。怎么样?

标签: javascript node.js ecmascript-6 error-handling


【解决方案1】:

如果找不到值则抛出错误。

if(!c.system) throw new Error("Missing system"); // This would fail if c.system is falsy

// In this case can be used:

if(!c.hasOwnProperty("system")) throw new Error("Missing system")

可以创建一个函数来检查这个。

function Check(objt, key, messageError){
    if(!objt.hasOwnProperty(key)) throw new Error(messageError)
}
Check(c, "system", "Missing system");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-14
    • 1970-01-01
    • 2020-10-20
    相关资源
    最近更新 更多