0

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.

5
  • 3
    Your second example doesn't really make sense. By the time callback is called, the error has already happened or not happened, and err is the error (if it did) or null (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.) Commented Sep 21, 2016 at 14:54
  • Try catch cannot optimize by V8! Commented Sep 21, 2016 at 14:54
  • You catch something that's thrown; here err is being passed in: the error has already happened. Commented Sep 21, 2016 at 14:56
  • 1
    The error passed to the callback is a result of the async operation which invokes the callback. The one you happen to catch within the callback is a run time error. Commented Sep 21, 2016 at 14:59
  • Consider using an assertion framework to handle the error in a callback. Or simply log the error in a if statement. Commented Sep 21, 2016 at 15:43

1 Answer 1

3

There is important difference - "error-first" approach is for asynchronous calls, try-catch is for synchronous.

If you're using some external libraries, it's up to them to determine how errors must be handled. Sometimes there are options (for example look at 'fs' module of node - synchronous functions throw errors and it's up to you to catch them, asynchronous ones return errors in callback)

If you're implementing your own functions, "error-first" approach looks better, just because it fits node's asynchronous nature.

(and another reason not to use try-catch - V8 optimizer may not optimize functions with this construction as good as if it wasn't there)

Sign up to request clarification or add additional context in comments.

1 Comment

Why is error-first only for async? I'm writing a synchronous function that can either return a result or an error. Is there any reason not to use error-first in that scenario?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.