I work mostly with nodejs (but I'm relevently new to javascript in general), but more specifically expressjs. They explicitly suggest using the try and catch pattern, but I've seen others suggest just doing the tried and true error first.
i.e.
callback(err, data) {
if (err) throw err;
//do something if no error was returned
}
instead of
callback(err, data) {
try {
//do something
} catch(err) {
//handle the error
}
}
Which one is widely considered the better way of doing things? Javascript is very ambiguous when it comes to "the one true way" of doing something.
callbackis called, the error has already happened or not happened, anderris the error (if it did) ornull(if it didn't). This is because of the asynchronous nature of most Node API calls, so there's this standard contract on callbacks: The first arg is an error (if any), the second is data (if any). (If the API were being designed today, it would use promises, and in fact there are bridging libs.)erris being passed in: the error has already happened.