NodeJS 使用axios处理异步等待语法错误

fdx2calv  于 2022-12-26  发布在  Node.js
关注(0)|答案(7)|浏览(228)

下面是我的代码块:

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

如你所见,我连接到外部服务器以获取令牌。这是有效的。现在,我想捕获一个错误,但这次不是用'throw new error',而是想将其发送给用户,所以我想使用类似下面的代码:

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

但是因为我不在路由处理程序里面,所以我不能使用"res",那么我怎么把它发送给用户呢?
谢谢大家!

qlfbtfca

qlfbtfca1#

对于axios版本-0. 19. 0以下的代码,在与async wait斗争了几个小时后工作。虽然不确定其他版本!

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

mitkmikd2#

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

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.')
  }
}

然后从路由处理程序中只返回catch最终异常

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异常系统可以很好地通过调用堆栈传递错误数据。

kokeuurv

kokeuurv3#

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

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!');
    }
}
au9on6nz

au9on6nz4#

你保持一个像isAuthError这样的标志,如果错误发生,发送它为真,如果isAuthError标志为真,在main函数中抛出错误,在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};
    }
  };

主函数

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

qc6wkl3g5#

try/catch不是一个好的解决方案,它的目的是捕获运行时错误,而不是来自axios的HTTP错误(如果错误由拦截器处理,然后通过return Promise.reject(error);传递回调用者
下面是拦截器示例

axios.interceptors.response.use(
  response => {
    //maybe process here
    return response;
  },
  error => {
    //do some global magic with error and pass back to caller
    return Promise.reject(error);
  }
);

让我们从无法运行的try/catch示例开始

for(let i=0; i<5;i++) {

    try{
       const result = async axios.get(`${/item/{i}}`);
    }
    catch(error) {
       //error undefined here, you would expect an error from pattern like axios.get(...).then(...).catch(real_http_error) 
    }
}

我发现这个模式可以工作。假设你想在一个循环中进行调用,以避免由于JS的异步特性而进行多个http调用。

for(let i=0; i<5;i++) {

    const result = async axios.get(`${/item/{i}}`).catch(error) {  //chain catch despite async keyword
       //now you access http error and you can do something with it
       //but calling break; or return; won't break for loop because you are in a callback
    }

    if(!result) { //due to http error
        continute; //keep looping for next call
        //or break; to stop processing after 1st error
    }
    
    //process response here, result.data...
}
bprjcwpo

bprjcwpo6#

保持async / await的优雅:

const result = await axios.post('/url', params)
    .catch((err) => {
       // deal with err, such as toggle loading state, recover click and scroll.
       this.loading = false;
       // recover the reject state before.
       return Promise.reject(err);
    });

this.data = result; // not exec when reject
wn9m85ua

wn9m85ua7#

优雅与TypeScript。

import axios, { AxiosResponse, AxiosError } from "axios";
...

const response: void | AxiosResponse<any, any> = await axios({
  headers: {
    Authorization: `Bearer ${XYZ}`,
    Accept: "application/json",
  },
  method: "GET",
  params: {
    ...
  },
  url: "https://api.abcd.com/...",
}).catch((error: AxiosError) => {
  if (error instanceof Error) {
    console.error(
      "Error with fetching ..., details: ",
      error
    );
  }
});

相关问题