【问题标题】:How can I return an error from a function?如何从函数返回错误?
【发布时间】:2021-04-26 08:44:37
【问题描述】:

假设我有一个这样的函数:

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

如果没有找到播放器,如何将 err 参数返回给 client 变量?例如:

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

我尝试通过 throw new Error('my error') 传递错误,但函数仍然没有得到它,我做错了什么?:(

【问题讨论】:

  • 请在提问时不要着急,检查您自己发布的代码是否有错误。创建一个minimal reproducible example。目前还不清楚你在追求什么。 - 毕竟。

标签: javascript node.js callback return


【解决方案1】:

所以你的第一直觉是正确的,你应该使用'throw'关键字来引发错误。要处理错误,您需要使用try/catch,就像我在下面所做的那样。

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

当在 try 块中执行的函数内部抛出错误时,执行会立即跳转到 catch 块,让您可以适当地响应错误。

【讨论】:

    【解决方案2】:

    为此检查 try/catch 语法。

    例如:

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

    要获得这种“错误”状态,当它触发时,您可以执行以下操作:

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

    【讨论】:

      【解决方案3】:

      我尝试了一些方法,但不确定这是否是您所追求的:

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

      在控制台中使用 a(0) 的值运行它 --> 会抛出一个新的错误和 a(5)

      【讨论】:

        猜你喜欢
        • 2021-05-30
        • 2023-04-09
        • 2021-03-07
        • 2017-02-26
        • 2020-04-29
        • 2018-01-20
        • 1970-01-01
        • 2023-03-08
        • 1970-01-01
        相关资源
        最近更新 更多