In JavaScript, if I have try catch blocks in a function that is meant to be called from another function, should I also put them in the calling function or just let the called functions handle them.
Here is some pseudo code to illustrate what I mean. I have two called functions, one and two. They are essentially the same but each calls a different API and throws an error if something goes wrong. Then I have two versions of a third function, one with a try-catch block and one without.
- Is one of these(function threes) a better practice than the other?
- Is there a still better way to do it?
function one async (){
try{
//await some value
// return the value
// if that doesn't work throw an error
} catch(error){
//handle error
}
}
function two async (){
try{
//await some value
// return the value
// if that doesn't work throw an error
} catch(error){
//handle error
}
}
function three-version-1 (){
try{
// await return value from one()
// do something with it
// if that doesn't work await return value from two()
// do something with that instead
// if that doesn't work throw an error
} catch(error){
//errors are handled in called functions but put handle them here anyway just in case
}
}
function three-version-2 async (){
// await return value from one()
// do something with it
// if that doesn't work await return value from two()
// do something with that instead
// errors are handled in called functions so no need to handle them here
}
catch
blocks re-throwing any of the exceptions?