【问题标题】:How to access try catch error in Javascript through api request?如何通过 api 请求访问 JavaScript 中的 try catch 错误?
【发布时间】:2020-10-10 18:15:38
【问题描述】:

我的 nodejs api 发送

res.status(401).json({ info: 'task cannot be done' }) 

作为一个错误,我尝试通过

在客户端捕获它
try {
      const resp = await axios.get('https://localhost:3000/getinfo')
      console.log('resp!!!', resp)
    } catch (error) {
      console.log('error' , error )
    }

虽然在我的网络选项卡上我可以看到以 JSON 格式显示的消息,但我不确定如何从错误中提取数据。

如何访问从服务器端发送的info

【问题讨论】:

    标签: javascript node.js reactjs axios


    【解决方案1】:

    使用error.response 获取客户端上从服务器接收到的实际错误

    console.log(error.response);
    

    【讨论】:

    • .response 显然是未定义的。
    • 不,@Hypothesis,不是。如果您的服务器以 4xx/5xx 错误响应,则您的错误对象包含一个响应字段。通常,这是我们最熟悉且最容易处理的错误。
    【解决方案2】:

    使用 axios 你可以处理错误

     const resp = await axios.get('https://localhost:3000/getinfo').catch(err=> 'Do whatever you want with the error');
    

    【讨论】:

      【解决方案3】:

      您可以使用其中一种:
      1.

           catch(error){
                  const { details } = error;
                  const message = details.map(i => i.message).join(',');
                  return res.status(400).json({ error: {message:message} })
      }
      
      1.  catch(err){
                let {message} = err;
                return res.status(400).json(
                   {
                     error: {
                          message: message,
                     }
                });
          }
        

      【讨论】:

      猜你喜欢
      • 2019-11-11
      • 2019-11-14
      • 2021-02-02
      • 2020-02-21
      • 1970-01-01
      • 2022-12-21
      • 1970-01-01
      • 2014-10-31
      • 2010-09-18
      相关资源
      最近更新 更多