Reputation: 4630
Today I discovered an error in my code that leads to callbacks potentially being executed more than once. The intended usage of try...catch was meant for JSON.parse() operation; however, an error has occurred right after it inside the callback itself.
var body='{}';
var callback=function (arg){
console.log('callback executed with arg='+arg);
arg? pack_michael(): pack_jolly();
}
try {
JSON.parse(body); //if JSON parse successful should callback once with true argument
callback(true);
} catch (e){
callback(false); //if JSON parse fails should callback once with false argument
}
Above code results in double callback printing this:
callback executed with arg=true
callback executed with arg=false
I can think of some ugly solutions like creating a variable and checking if an error has occurred or nesting another unnecessary try...catch, but isn't there any neat solution to deal with this?
Upvotes: 0
Views: 412
Reputation: 919
Add new try/catch
around callback
try {
JSON.parse(body);
try {
callback(true);
} catch(err) { console.log("Error in callback")}
} catch (e){
callback(false); //if JSON parse fails should callback once with false argument
}
Upvotes: 0
Reputation: 371168
Call the callback after the try
/catch
:
let parseOk = false;
try {
JSON.parse(body);
parseOk = true;
} catch (e){
// parseOk is already false
}
callback(parseOk);
If you also want to catch errors in the callback itself, you can surround it in a different try
/catch
, but that's separate from errors that occur in the JSON.parse
, so they shouldn't be combined.
Upvotes: 4