koketi3032
koketi3032

Reputation: 1

How can I return an error from a function?

Let's say I have a function like this:

const getPlayer = (id) => {
  return players[id;]
}
//--------------------------
const client = getPlayer(9);

How can I return the err parameter to the client variable if no player is found? For example:

if (client.err) { 
//do something
}

I tried passing the error via throw new Error('my error') , but the function still doesn't get it, what am I doing wrong?:(

Upvotes: 0

Views: 1054

Answers (3)

Mohd Jawwad Hussain
Mohd Jawwad Hussain

Reputation: 135

I have tried something but not sure if this is what you are after:

let a = (x) => {
  if (x == 0) {
    throw new Error("Votes are zero");
  } else {
    return x;
  }
};

Run it in the console with the values as a(0) --> will throw you a new error and a(5)

Upvotes: 0

Artem Myazitov
Artem Myazitov

Reputation: 1

Checkout try/catch syntax for that.

For example:

const getPlayer = (id) => { 
    if (!id) {
        throw new Error('no id provided');
    }

    return players[id]
}

To get this "error" state, when it triggers you can do following:

try {
    const client = getPlayer(null);
} catch(error) {
   console.log(error.message);
}

Upvotes: 0

Ben Wainwright
Ben Wainwright

Reputation: 4651

So your first instinct was correct, you should use the 'throw' keyword to raise an error. To act on the error you need to use try/catch like I've done below.

const getPlayer = (id) => {
  if(id in players) {
     return players[id];
  }
  throw new Error("Oh noes...!");
}

try {
   const client = getPlayer(9);
} catch(error) {
   console.log(error.message);
}

When an error is thrown inside a function being executed in a try block, execution immediately jumps to the catch block, allowing you to respond to the error appropriately.

Upvotes: 1

Related Questions