Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
69 views
in Technique[技术] by (71.8m points)

javascript - 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?:(

question from:https://stackoverflow.com/questions/65835739/how-can-i-return-an-error-from-a-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...