简体   繁体   English

如何通过api请求访问Javascript中的try catch error?

[英]How to access try catch error in Javascript through api request?

My nodejs api sends我的 nodejs api 发送

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

as an error and I try to catch it on the client side via作为错误,我尝试通过在客户端捕获它

try {
      const resp = await axios.get('https://localhost:3000/getinfo')
      console.log('resp!!!', resp)
    } catch (error) {
      console.log('error' , error )
    }

Although on my.network tab I can see the message coming in JSON format I am not sure how to extract data from error.虽然在 my.network 选项卡上我可以看到以 JSON 格式出现的消息,但我不确定如何从错误中提取数据。

How can I access info which is sent from the server side.如何访问从服务器端发送的info

use error.response to get the actual error received from the server on the client使用error.response获取客户端从服务器接收到的实际错误

console.log(error.response);

With axios you can handler the error使用 axios 您可以处理错误

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

You can use one of these:您可以使用其中之一:
1. 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, } }); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM