在async/await中处理错误

91 阅读1分钟

背景

async/await相信大家都不陌生,这个极大地解决了我们使用callback处理回调问题,但是你对他处理异常真的了解吗?处理不好,有可能拿到的结果跟预期的不一致。

介绍

首先看下如下代码

async getData() {
   const data = await this.$axios.get('api/v1/user_list');
   
   console.log(data);
   
   return data;
}

await getData();

console.log('test');

当以上代码执行,接口报错的时候,输出是什么?

浏览器控制台,直接输出接口错误,没看到test输出, 也没有data
代码在await处被中断,没有继续往下走。

捕获错误

有两种捕获方式:

  1. try/catch
  2. .catch

使用try/catch捕获

async getData() {
    let result = [];
    
    try {
     result =  await this.$axios.get('api/v1/user_list');
     
     console.log(result);
    } catch(e) {
     console.log(e);
    } 
    
    return result;
}

await getData();

console.log('test');

以上代码执行之后,除了输出e错误之外,还能输出了test,没有输出result
代码在await处被中断,没有继续往下走。

使用.catch捕获

async getData() {
   const result =  await this.$axios.get('api/v1/user_list').catch(e => {
       console.log(e);
   });
   
   console.log(result);
  
   return result;
}

await getData();

console.log('test');

以上代码执行之后,除了输出e错误之外,还能输出了testresultundefined
代码没有在await处中断,代码能继续往下走。

当错误的时候,如何让result为错误信息呢?此时需要在.catch那里进行返回即可

async getData() {
   const data =  await this.$axios.get('api/v1/user_list').catch(e => {
       console.log(e);
       
       return e;
   });
   
   console.log(data);
  
   return data;
}

await getData();

console.log('test');

以上代码执行之后,除了输出e错误之外,还能输出了test以及resulte的值

处理返回数据,解决返回提示void

有时候我们需要对返回数据做一些处理,在await中使用了thencatch之后之后,如果没有显示return数据,那么外层将会提示返回是void。如下result的值会一直是undefined

async getData() {
   const result =  await this.$axios.get('api/v1/user_list').catch(e => {
       console.log(e);
       
       return e;
   }).then(res => {
       // do somthing
   });
   
   console.log(result);
  
   return result;
}

await getData();

因为await返回的是一个promise,进行链式处理之后需要在链式中返回

改造代码,在then中返回数据

async getData() {
   const result =  await this.$axios.get('api/v1/user_list').catch(e => {
       console.log(e);
       
       return e;
   }).then(res => {
       // do somthing
       return res;
   });
   
   console.log(result);
  
   return result;
}

await getData();

以上代码运行就能愉快地拿到数据了

总结

使用.catch或者.then处理了await结果的时候,需要在两个回调中继续返回数据或者一个promise,外面函数调才能拿到结果,不然返回的是undefined

await语句没有.catch异常处理的时候,代码不会继续往下走。

相关文章

async-await-error-handling