分别处理同一实例的多个异常

时间:2019-11-19 17:29:21

标签: javascript typescript exception

如果我对另一个无法更改的类有多个方法调用,每个方法都可能引发相同的异常,那么在不执行其余函数的情况下,我将如何分别处理每个异常?

示例:

async mightThrowExceptions() {

    var call1 = await this.api.sampleMethod(); //Might throw exception of instance 'E'
    //Mustn't be called if call1 threw exception
    var call2 = await this.api.dependantFrom1(call1); //Might throw exception of instance 'E'
    //Mustn't be called if call2 threw exception
    var call3 = await this.api.dependantFrom2(call2); //Might throw exception of instance 'E'

    /*
    if call1 threw exception, do:
    console.log('call1 threw exception');

    if call1 threw exception, do:
    console.log('call2 threw exception');

    if call1 threw exception, do:
    console.log('call3 threw exception');
    */
}

1 个答案:

答案 0 :(得分:1)

您可以嵌套尝试捕获:

 try {
   const a = await getA();
   try {
       const b = await getB(a);
       try {
        const c = await getC(b);
       } catch(e) {
         // handle c error, no control flow!
       }
    } catch(e) {
       // handle b error, no control flow!
    }
 } catch(e) {
    // handle c error, no control flow!
 }

如果这些功能抛出不同的结果,那么适当的设计将是可以做到的:

 try {
    await getC(await getB(await getA()));
 } catch(error) {
   if(error instanceof AError) {
      // ...
   } else if(error instanceof BError) {
       //...
    } else if(error instanceof CError) {
        //...
    } //?
 }