Michael Schwartz
Michael Schwartz

Reputation: 8415

Return error if no parameter in function

What are some good practices for returning errors from a function that requires parameters are not executed within the function?

function someFunction(hello, world) {
  if (!hello) {
    console.error("missing first parameter")
  } else if (!world) {
    console.error("missing second parameter")
  } else if (!hello && !world) {
    console.error("missing both parameters")
  }
}

someFunction("hola");

Upvotes: 0

Views: 1607

Answers (2)

bugwheels94
bugwheels94

Reputation: 31920

Best way to detect absent arguments is using typeof( in case undefined being overwritten) and then return accordingly

if (typeof hello === 'undefined') {
    console.error("missing first parameter")
    return new Error('missing first parameter')
.....

After that you will be able to match the output using instanceof

As suggested in comments put the last condition above other conditions and also you cannot miss first argument and get second argument because in that case your second argument will become first argument

function some(hello, world) {
  if (typeof hello === 'undefined' && typeof world === 'undefined') {
    console.error("missing both parameter")
    return new Error("missing both parameter")
  } else if (typeof world === 'undefined') {
    console.error("missing second parameters")
    return new Error("missing second parameter")
  }
}
console.log(some() instanceof Error)
console.log(some('a') instanceof Error)

Upvotes: 2

Karim
Karim

Reputation: 8632

you can wrap your code inside a try catch block and throw any exception triggered from your code to the caller.

function someFunction(hello, world) {
  try{
   //use any of the arguments
  }catch(err){
   throw new Error('something went wrong');
  }
}

another approach that maybe could suit your case is to use default parameters to keep the code safe.

function someFunction(hello, world) {
  hello = hello || {};
  world = world || {};
  //hello and world are initialized here in any case
}

Upvotes: 1

Related Questions