Skip to content

Instantly share code, notes, and snippets.

@krazylearner
Last active October 3, 2015 11:49
Show Gist options
  • Select an option

  • Save krazylearner/423c2aab7e49c58ed9d6 to your computer and use it in GitHub Desktop.

Select an option

Save krazylearner/423c2aab7e49c58ed9d6 to your computer and use it in GitHub Desktop.
nodejs design patterns applicable for other programming languages

##Patterns for writing functions ###how do you deliver errors to the code that called your function ?

''' Document what your function does, including what arguments it takes (including their types and any other constraints), what it returns, what errors can happen, and what those errors mean. So if you're writing a new function, you have to tell your callers what errors can happen and what they mean. '''

three basic patterns for a function to deliver errors.

Throw, Callback, or EventEmitter

throw

throw delivers an error synchronously — that is, in the same context where the function was called. If the caller (or the caller's caller, ...) used try/catch, then they can catch the error. If none of the callers did, the program usually crashes. (The error can also be handled by domains or the process-wide "uncaughtException" event, which are discussed below.)

Callbacks

Callbacks are the most basic way of delivering an event asynchronously. The user passes you a function (the callback), and you invoke it sometime later when the asynchronous operation completes. The usual pattern is that the callback is invoked as callback(err, result), where only one of err and result is non-null, depending on whether the operation succeeded or failed.

EventEmitter

For more complicated cases, instead of using a callback, the function itself can return an EventEmitter object, and the caller would be expected to listen for error events on the emitter. 
Example
For objects that represent complex state machines, where a lot of different asynchronous things can happen. For example, a socket is an event emitter that may emit "connect", "end", "timeout", "drain", and "close". It's natural to make "error" just another type of event that the socket can emit. When using this approach, it's important to be clear about when "error" is emitted, whether any other events may be emitted, what other events may be seen at the same time (e.g., "close"), what order they happen in, and whether the socket is closed at the end of it.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment