Home > Software engineering >  How to fail if missing a function parameter
How to fail if missing a function parameter

Time:11-03

When make a function, I check that the required parameters are filled in as seen below.

Question

It is not really a good way, as all it does is assigning a default value to a missing parameter. I'd much rather have that execution stops and tells me which function is missing a parameter. How is that done, if possible?

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);
};

CodePudding user response:

Throwing an error if doesnt find the value.

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")

Can create a function to check this.

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