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 {
  } catch (e) {
    if (env === "development" || env === "test") {

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

Google OAuth with Devise

Git LFS on Heroku

The Two Metrics You Need

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