The Safely Pattern

The Safely Pattern is a simple one. It allows you to tag non-critical code by wrapping it in a function. It’s built on top of exception handling and follows these rules:

  1. Raise exceptions in development and test environments
  2. Catch and report exceptions in other environments

Here’s a basic implementation in JavaScript:

function safely(nonCriticalCode) {
  try {
    nonCriticalCode();
  } catch (e) {
    if (env === "development" || env === "test") {
      throw(e);
    }
    report(e);
  }
}

Its advantages over typical exception handling are:

  1. It’s easier to write and debug code when errors aren’t caught in development and test environments
  2. It allows you to keep reporting DRY

It’s recommended to mark exceptions when reporting so it’s clear they were handled with this pattern. One way of doing this is to prefix the exception message with [safely].

There are currently implementations in Ruby and JavaScript.

Published December 6, 2016


You might also enjoy

New Rails App Checklist

Introducing Archer: Rails Console History for Heroku, Docker, and More

Bulk Upsert in Ruby/Rails


All code examples are public domain.
Use them however you’d like (licensed under CC0).