简体   繁体   中英

Run external catch from nested try

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

As in the code above. If was error in send function, prepare_to_send function don't change back global variable InProgress to false, beacuse _callback and catch from prepare_to_send are not runned.

Is this possible without changing send function?

If _callback isn't an asynchronous function you can re-throw the error, or even a new one :

 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(); 

But if _callback is asynchronous as you seem to state, then you'll have to deal with promises all the way, ie. adapt the whole code. You also can add an error callback as stated in comment section :

 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(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM