javascript异常捕获探讨

304 阅读1分钟

问题

  • 在javascript中try/catch中包含的方法或异步方法是否可以在外部进行捕获呢?
  • 当一次需要调用/保存多个方法时,如何保证前一个接口出错后不再进行后面接口调用,并对异常是否可以类似java一样在最外层进行统一处理。

实现

如下示例可以实现统一处理接口异常。

const callApi1 = async () => {
    //保存前数据处理
    ...
    let res = await Promise.resolve({ code:500, msg: 'xxx' });
    
    if(res.code != 200){
        throw new Error(res.msg);
    }
    //保存后操作
    ...
}

const saveMethod = async () => {
    try{
        await callApi1();  //异步方法
        await callApi2();  //异步方法
        await callApi3();  //异步方法
    }catch(e){
        //该处统一处理错误
    }
}

saveMethod();

测试过程

1.捕获方法内异常

try{
  err();
}catch(e){
  console.log(e)
}

function err(){
  throw new Error('something is error')
}

异常可以被捕获

2.捕获嵌套方法内异常

try{
  outer();
}catch(e){
  console.log(e)
}

function outer(){
  inner();
}

function inner(){
  throw new Error('something is error')
}

异常可以被捕获

3.捕获异步方法内异常

try{
  err();
}catch(e){
  console.log(e)
}

function err(){
  setTimeout(() => {
    throw new Error('something is error')
  },500)
}

异常不能被捕获

4.捕获异步方法内异常-使用async/await

(async () => {
  try{
    await err();
  }catch(e){
    console.log(e)
  }

  function err(){
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        //throw new Error('something is error')
        reject('something is error');
      },500)
    })
  }
})();

异常可以被捕获