使用axios处理来自异步等待语法的错误

时间:2018-09-26 07:17:53

标签: node.js express

这是我的大部分代码:

  const getToken = async () => {
    try {
      const token = await axios.post(keys.sessionURL, {
        email: keys.verificationEmail,
        password: keys.verificationPassword,
      });
    } catch (err) {
      throw new Error('Unable to establish a login session.'); // here I'd like to send the error to the user instead
    }
  };

因此您可以看到我正在连接到外部服务器以获取令牌。那行得通。现在,我想捕获一个错误,但是这次不包含“引发新错误”,但是我想将其发送给用户,所以我想改成这样:

res.status(401).send('Unable to get a token');

但是因为我不在路由处理程序中,所以不能使用'res'。那我该如何发送给用户呢?

谢谢!

4 个答案:

答案 0 :(得分:6)

对于axios版本0.19.0以下的代码,经过数小时与async await的纠缠后,它们才能正常工作。但是不确定其他版本!

catch(error){
console.log(error.response.data.error)
}

希望有帮助!

答案 1 :(得分:1)

您保留一个isAuthError之类的标志,如果发生错误,则将其发送为true;如果标志isAuthError为true,则在主函数中将其抛出错误并进行catch处理,否则执行您的操作。我在下面添加了一个示例。希望对您有帮助

const getToken = async () => {
    try {
      const token = await axios.post(keys.sessionURL, {
        email: keys.verificationEmail,
        password: keys.verificationPassword,
      });
      return {token, isAuthError: false};
    } catch (err) {
      // throw new Error('Unable to establish a login session.'); // here I'd like to send the error to the user instead
      return {err, isAuthError: true};
    }
  };

mainFunction

app.post('/login', async (req, res)=>{
  try{
    // some validations

    let data = await getToken();
    if( data.isAuthError){
      throw data.err;
    }
    let token = data.token;
    //do further required operations
  }catch(err){
     //handle your error here with whatever status you need
     return res.status(500).send(err);
  }
})

答案 2 :(得分:0)

您可以保留几乎相同的功能

const getToken = async () => {
  try {
    const token = await axios.post(keys.sessionURL, {
      email: keys.verificationEmail,
      password: keys.verificationPassword,
    })
  } catch (err) {
    throw new Error('Unable to get a token.')
  }
}

然后从您的路由处理程序中捕获最终的异常

app.get('/endpoint', async (req, res) => {
  try {
    const token = await getToken()

    // Do your stuff with the token
    // ...

  } catch (err) {
     // Error handling here
     return res.status(401).send(err.message);
  }
})

默认的js异常系统非常适合通过调用堆栈传递错误数据。

答案 3 :(得分:0)

在我的解决方案中,我使用:

try{
    let responseData = await axios.get(this.apiBookGetBookPages + bookId, headers);
    console.log(responseData);
}catch(error){
    console.log(Object.keys(error), error.message);
}

如果失败,我们将收到如下错误消息:

[ 'config', 'request', 'response', 'isAxiosError', 'toJSON' ] 
'Request failed with status code 401'

我们还可以获取状态代码:

...
}catch(error){
    if(error.response && error.response.status == 401){
            console.log('Token not valid!');
    }
}