【问题标题】:Error handling in Async Await API callingAsync Await API 调用中的错误处理
【发布时间】:2026-01-20 17:30:02
【问题描述】:

我有一个使用节点提取的脚本,并且在进行提取调用时是异步的。我试图实现错误处理,但我没有找到解决方案。下面提供了我的代码的 sn-p,我需要找到一种方法来检测被调用的 API 何时发回错误。

var url = "https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=API KEY";
var payload = {
  email: email,
  password: password,
  returnSecureToken: true

};

 var options = {
     method: 'post',
     contentType: 'application/json',
     body: JSON.stringify(payload)
  };
    var res = await fetch(url, options);
  var result = await res.json();
response.send(JSON.stringify(result))

谢谢,感谢任何解决此问题的尝试!

【问题讨论】:

  • 您的 URL 不正确,在 URL 的末尾需要 API KEY,您需要获取私有 API 密钥才能使 URL 正常工作。
  • 您需要将 await 调用包装在 try-catch 块中,并从 catch 块中读取异常。试试这个:*.com/questions/44663864/…
  • 听说过 try-catch 块吗?
  • @StephenP 我不是那个意思,但是对不起大家

标签: javascript node.js async-await fetch node-fetch


【解决方案1】:

以下将起作用。

async function f() {

  try {
    let response = await fetch('/something');
    let user = await response.json();
  } catch(err) {
    // catches errors both in fetch and response.json
    alert(err);
  }
}

【讨论】:

    【解决方案2】:

    我想通了。只需检查响应代码即可。

    async function helloWorld() {
        url ="someurl"
        let response = await fetch(url);
        let result = await response.json();
        if(response.status == 400){
        res.status(400).send(JSON.stringify(result)
      }
    }
    

    【讨论】:

      【解决方案3】:

      我也有同样的情况,在这篇文章中找到了答案。

      Handling error from async await syntax with axios

      因为像 axios 已经更新了这个,我就是这样做的。

      try {
          const res = await publicRequest.post("/users/login",{email:email,password:password});
          console.log(res);
          setIsLoading(false);
        } catch (error:any) {
          console.log(error.response.data.error)
          setError(error.response.data.error);
          setIsLoading(false);
        }
      

      【讨论】: