从嵌套try

时间:2017-09-19 10:36:24

标签: javascript nested try-catch

inProgress = false;

//async function which send value to device
function send(_callback){ 
   try{ 
      // code that generate error
      _callback(); 
   }catch(err){
      console.log("_callback doesn't start");
   }
}

function prepare_to_send(){
   try{
       inProgress= true; 
       send(function(){ 
          send(function(){ // isn't runned, because was err inside send
             inProgress = false;
          })
       });
   }catch(err){
      inProgress = false;
   }
}

如上面的代码所示。 如果发送函数出错,则prepare_to_send函数不会将全局变量InProgress更改为false,不会运行来自prepare_to_send的beacuse _callback和catch。

这可以不改变发送功能吗?

1 个答案:

答案 0 :(得分:0)

如果_callback不是异步函数,您可以重新抛出错误,甚至是新错误:

inProgress = false;

//async function which send value to device
function send(_callback) {
  try {
    // code that generate error
    _callback();
  } catch (err) {
    console.log("_callback doesn't start");
    throw err;
  }
}

function prepare_to_send() {
  try {
    inProgress = true;
    send(function() {
      throw 'error';
    });
  } catch (err) {
    inProgress = false;
    console.log(err);
  }
}

prepare_to_send();

但如果_callback是异步的,你似乎要说明,那么你将不得不一直处理承诺, ie。适应整个代码。您还可以添加错误回调,如评论部分所述:

inProgress = false;

//async function which send value to device
function send(_callback, errorCallback) {
  // code that generate error
  _callback(errorCallback);
}

function prepare_to_send() {
  inProgress = true;
  send(function(errorCallback) { // Your callback have to call another function on error
    try {
      throw 'error';
    } catch (err) {
      errorCallback();
    }
  }, function() {
    inProgress = false;
    console.log('error occured');
  });
}

prepare_to_send();