Error handling done right, in Rails and JavaScript

TL;DR

Difficulty: Intermediate

Good error handling is a set of small, deliberate decisions written into code.

  • Rescue the error you expect by name, never everything, and give the business its own error classes.
  • Put a timeout on every network call and retry in one place only, with growing random waits.
  • Make payments safe to retry with an idempotency key stored on the order, and treat a provider's server error as an unknown outcome.
  • In JavaScript check response.ok, never leave a promise unattended, and use error boundaries.
  • Log ids and reasons, not people, and alert a person only when a person must act.

The theory of errors is tidy. Real code is where it goes wrong: a bare rescue that hides a bug, a payment call with no timeout, a retry that charges a customer twice. This chapter takes one invented tea shop in Bristol and rewrites its error handling, pattern by pattern, in Ruby on Rails and JavaScript.

From theory to code

The chapter on errors and exceptions explained the ideas: an expected error is part of the business, an unexpected one is a bug, and for every error you decide whether to retry, tell the customer, alert the developer or stop. This chapter is the code that carries those decisions out.

All the examples use one invented business. Fernhill Tea is an online tea shop in Bristol at fernhilltea.example. It sells loose tea and monthly subscriptions, takes card payments through a payment provider, offers discount codes, tracks stock and sends order emails. Its developer is Priya. The back end is Ruby on Rails 8, the subscription page is React. The payment provider in the code is made up (payments.example), but every behaviour it shows follows the documentation of real providers, and I cite that documentation where it matters.

Rescue the error you expect, by name

In Ruby, raise throws an exception and rescue catches it. A bare rescue with no class after it catches StandardError and everything below it1. That sounds safe. It is the opposite. Almost every bug in Ruby code is a StandardError: a typo in a method name (NoMethodError), a missing value (KeyError), a wrong type (TypeError). A bare rescue catches all of them and hides them behind whatever fallback you wrote for the one problem you had in mind.

The rule is simple. Write the name of the error you expect after rescue. Let everything else travel up, where the framework shows an error page and the error reporter records it. The same rule holds in JavaScript, where a catch block catches everything, so you check what you caught and throw anything you did not expect again.

Example: looking up a discount code

Fernhill Tea's basket accepts codes such as SPRING10. Here is the first version Priya finds in the code base:

def apply_discount(code)
  discount = DiscountCode.find_by!(code: code.upcase)
  self.discount_pence = discount.amount_for(self)
rescue
  errors.add(:discount_code, "is not valid")
end

Line by line: find_by! looks the code up and raises ActiveRecord::RecordNotFound when there is no such code. amount_for works out the discount for this basket. The bare rescue turns any problem into "is not valid".

Now imagine amount_for has a bug and calls a method that does not exist. Every customer with a perfectly good code is told it is invalid. Nobody gets an alert, because nothing ever fails loudly. The shop just sells less in spring and nobody knows why.

The fixed version names the one error that really means "this code does not exist":

def apply_discount(code)
  discount = DiscountCode.find_by!(code: code.upcase)
  self.discount_pence = discount.amount_for(self)
rescue ActiveRecord::RecordNotFound
  errors.add(:discount_code, "is not valid")
end

An unknown code still gets the friendly message. A bug in amount_for now raises NoMethodError, reaches the error page and the error reporter, and Priya fixes it the same morning.

Give your business its own error classes

Library errors describe what went wrong technically: a timeout, a 402 status, a missing record. Your controllers and your customers care about what it means for the business: the card was declined, the provider is down, the tea is sold out. A small set of your own error classes translates one into the other, once, in the place that knows both.

Keep the set small and shallow. One base class for the whole shop, a branch for payments, and one class for each outcome your code treats differently. If two errors are always handled the same way, they are one class.

Example: the tea shop's error classes

module FernhillTea
  class Error < StandardError; end

  class PaymentError < Error; end
  class CardDeclined < PaymentError
    attr_reader :decline_code

    def initialize(decline_code)
      @decline_code = decline_code
      super("card declined: #{decline_code}")
    end
  end
  class PaymentProviderUnavailable < PaymentError; end
  class PaymentOutcomeUnknown < PaymentError; end

  class OutOfStock < Error; end
end

FernhillTea::Error inherits from StandardError, so it behaves like any normal Ruby error. PaymentError groups everything about taking money. CardDeclined carries the reason the bank gave (insufficient_funds, for instance), because the message to the customer depends on it. PaymentProviderUnavailable means "we could not reach the provider, nothing happened". PaymentOutcomeUnknown means "the provider answered with a server error, and we do not know whether money moved". That last distinction is the most important line in the file, and the payment section explains why.

Because of the hierarchy, code that only cares that "something about payment failed" can rescue FernhillTea::PaymentError, and code that needs the detail rescues the exact class.

Turn errors into answers in one place with rescue_from

If every controller action has its own begin and rescue, the same message gets written five times, slightly differently each time. Rails offers rescue_from: you register an error class once in a controller, and Rails calls your handler whenever an action raises that error2. Errors you do not register still reach the standard error pages (public/404.html, public/500.html), which you can style to match the shop.

Example: the checkout controller

class CheckoutsController < ApplicationController
  rescue_from FernhillTea::CardDeclined, with: :card_declined
  rescue_from FernhillTea::OutOfStock, with: :out_of_stock
  rescue_from FernhillTea::PaymentProviderUnavailable, with: :provider_unavailable
  rescue_from FernhillTea::PaymentOutcomeUnknown, with: :outcome_unknown

  def create
    @order = current_basket.place_order!
    charge_id = PaymentGateway.new.charge(@order)
    @order.mark_paid!(charge_id)
    redirect_to order_path(@order)
  end

  private

  def card_declined(error)
    flash.now[:alert] = "Your bank declined the card, so nothing has been charged. " \
                        "Please try another card or check with your bank."
    render :new, status: :unprocessable_content
  end

  def out_of_stock(error)
    redirect_to basket_path, alert: "Sorry, one of your teas has just sold out. " \
                                    "Your basket shows what is still available."
  end

  def provider_unavailable(error)
    flash.now[:alert] = "Card payments are not responding right now and nothing has been charged. " \
                        "Please try again in a few minutes."
    render :new, status: :service_unavailable
  end

  def outcome_unknown(error)
    ReconcilePaymentJob.perform_later(@order)
    redirect_to order_path(@order), notice: "We are confirming your payment with the bank. " \
                                            "You will get an email within a few minutes."
  end
end

The four rescue_from lines map each business error to a private method, so the create action is the happy path only. Each handler tells the customer what happened and what to do next, in plain words, without blame. The declined card and the unreachable provider both say "nothing has been charged", because that is the first thing a customer worries about and in both cases it is true.

The unknown outcome is different. The customer is not asked to pay again, because they may already have paid. A background job asks the provider what really happened and finishes the order or releases it. A NoMethodError in place_order! is not on the list, so it reaches the 500 page and the error reporter, exactly as it should.

Clean up with ensure, whatever happens

Some code opens something that must be closed: a temporary file, a lock, a connection. If an error happens halfway, the closing line never runs, and the leftovers pile up until the disk is full or the lock blocks everyone. Ruby's ensure block runs whether the code above it succeeded, raised an error or returned early1. JavaScript has the same idea in finally.

Example: the nightly orders export

Every night Fernhill Tea writes the day's orders to a CSV file for the bookkeeper:

def export_orders(orders)
  file = Tempfile.new(["orders", ".csv"])
  orders.each { |order| file.puts([order.number, order.total_pence].join(",")) }
  file.close
  BookkeepingUpload.call(file.path)
ensure
  file&.close!
end

Tempfile.new creates a file in the system's temporary folder. The loop writes one line per order. BookkeepingUpload.call sends it. The ensure line runs in every case and close! closes the file and deletes it. The &. means "only if file exists", which covers the rare case where creating the file was the thing that failed. If the upload fails, the error still travels up to the job that called this method, but no stray file with order data is left on the server.

Put a timeout on every network call

A network call that never answers is worse than one that fails. A failure returns at once and your code can react. A hang ties up a web server thread, and a Rails server has only a handful of them. If the payment provider or the courier's rate service goes slow, every checkout waits, the threads run out, and the whole shop stops answering, including pages that have nothing to do with payment.

Ruby's Net::HTTP waits 60 seconds by default before it gives up reading an answer3. A customer gives up long before that. So every call that leaves your server gets two explicit limits: how long to wait for the connection (the open timeout) and how long to wait for the answer (the read timeout).

Example: choosing the checkout timeouts

Priya looks at the provider's status page history and the shop's own logs. A normal charge answers in under two seconds. So she sets:

  • open timeout: 2 seconds, because a connection that takes longer is not going to be healthy
  • read timeout: 8 seconds, four times the normal answer, so a slow but working provider still succeeds

The numbers are her judgement for this shop, not a universal rule. The rule is that the number is written down on purpose, never left at a default nobody chose.

Retry only what is safe to retry

Some errors are temporary: a connection reset, a timeout, a provider having a bad minute. Trying again a moment later often works. Other errors are permanent: a declined card stays declined, an invalid request stays invalid. Retrying those only adds load and delay.

Retries also cost something. Marc Brooker of Amazon describes them as "selfish": a client that retries spends more of the server's time to improve its own chance of success4. When many layers of a system each retry on their own, the extra work multiplies:

N=tLN = t^{L}

where NN is the number of calls that reach the bottom layer for one original request, tt is the number of tries each layer makes (the first try plus its retries), and LL is the number of layers that retry. Repeated multiplication like this is the same mechanism as compound growth, explained in Foundations: growth rates and compounding.

Example: three tries at five layers

Brooker's own example is a request that passes through five layers, each trying three times, in front of a database that has started to fail under load4. The calculation:

N=35=243N = 3^{5} = 243

Here t=3t = 3 and L=5L = 5. One customer click becomes 243 queries against a database that was already struggling, which makes recovery unlikely. The lesson for Fernhill Tea: retry in one place only, as close to the customer as possible, and let the layers below fail fast.

Why retries do not save you in an outage

If attempts failed independently, retries would be close to magic:

P(all fail)=pkP(\text{all fail}) = p^{k}

where pp is the chance that one attempt fails and kk is the number of attempts. The idea of independent events is explained in Foundations: probability.

Example: a bad minute against a real outage

On a normal day, say 1 in 20 calls to the provider hits a passing network problem, so p=0.05p = 0.05. With three attempts:

P(all fail)=0.053=0.000125P(\text{all fail}) = 0.05^{3} = 0.000125

That is about one checkout in 8,000. The retry has earned its place. Now suppose the provider is down for ten minutes. The attempts are no longer independent: if the first fails, the second fails too, so pp is close to 1 and pkp^{k} is close to 1 however many times you try. Retries smooth over brief problems. They do nothing for an outage except add load, which is why the number of attempts must be small and the circuit breaker further down exists.

Exponential backoff with jitter

When you retry, wait first, and wait longer each time (exponential backoff), so a struggling service gets room to recover. Add randomness to the wait (jitter), so a thousand clients that failed at the same moment do not all come back at the same moment. Brooker compared several schemes and found that adding jitter cut the total work substantially, calling jittered backoff a standard approach for remote clients5. The scheme he calls "Full Jitter" picks the wait at random between zero and a cap that doubles with each attempt:

dn=random(0, min⁡(c, b⋅2n))d_n = \text{random}\left(0,\ \min\left(c,\ b \cdot 2^{n}\right)\right)

where dnd_n is the wait before retry number nn (counting from n=0n = 0), bb is the base wait, cc is the longest wait you ever allow, and random(0,x)\text{random}(0, x) is a random number between 00 and xx. The doubling 2n2^{n} is again compounding, see Foundations: growth rates and compounding.

Example: the waits at the tea shop

Priya sets b=0.5b = 0.5 seconds and c=8c = 8 seconds. The upper limit of each wait:

  • before retry 0: min⁡(8, 0.5⋅20)=0.5\min(8,\ 0.5 \cdot 2^{0}) = 0.5 seconds
  • before retry 1: min⁡(8, 0.5⋅21)=1\min(8,\ 0.5 \cdot 2^{1}) = 1 second
  • before retry 2: min⁡(8, 0.5⋅22)=2\min(8,\ 0.5 \cdot 2^{2}) = 2 seconds
  • before retry 3: min⁡(8, 0.5⋅23)=4\min(8,\ 0.5 \cdot 2^{3}) = 4 seconds
  • before retry 4: min⁡(8, 0.5⋅24)=8\min(8,\ 0.5 \cdot 2^{4}) = 8 seconds, the cap

The actual wait is a random point below each limit, so one client might wait 0.3 seconds and the next 0.9. For the checkout she allows three attempts in total, so two waits. The worst case a customer can sit in front of the spinner is three full read timeouts plus the two longest waits:

3⋅8+0.5+1=25.5 seconds3 \cdot 8 + 0.5 + 1 = 25.5 \text{ seconds}

That is three attempts times the 8 second read timeout, plus the caps d0≤0.5d_0 \le 0.5 and d1≤1d_1 \le 1. Long, but bounded, and every second of it is a second in which the payment can still succeed. Without the limits it could have been minutes.

Idempotency keys make a payment safe to retry

Here is the trap in retrying a payment. Fernhill Tea sends a charge, the provider takes the money, and the answer gets lost on the way back. From the shop's side that looks exactly like a timeout. A naive retry charges the customer a second time.

The fix is an idempotency key. An operation is idempotent when doing it twice has the same effect as doing it once. The client creates a unique key for one payment and sends it with the request. If the provider sees the same key again, it does not charge again, it returns the result of the first request. Stripe's documentation describes exactly this: keys of up to 255 characters, ideally a random V4 UUID, never personal data such as an email address, and keys that may be removed once they are at least 24 hours old6. Its guidance on failures adds two rules worth following with any provider: when a connection fails, retry with the same key and the same parameters, and treat a server error (status 500 and above) as an unknown outcome to reconcile before you start a new operation7.

Example: the same lost answer, twice

A customer orders £42.50 of Assam and Darjeeling. The provider takes the money, but the answer times out on the way back.

Without a key: the shop retries, the provider sees a brand new charge and takes another £42.50. The customer sees two payments on their banking app, emails in a hurry, and Priya spends the afternoon refunding.

With a key: the order was given the key 6f1c2d0e... when it was created. The retry sends the same key. The provider recognises it, charges nothing more and returns the original charge. The customer pays £42.50 once and never knows anything went wrong.

The key belongs to the order, not to the request. That is why Priya stores it on the order record when the order is created, so every retry, from any process, sends the same one.

Example: the payment call, from fragile to robust

Everything so far comes together in one class. Here is the version Priya inherited:

class PaymentGateway
  def charge(order)
    uri = URI("https://api.payments.example/v1/charges")
    response = Net::HTTP.post_form(uri, amount: order.total_pence, currency: "gbp", source: order.card_token)
    JSON.parse(response.body)["id"]
  rescue
    nil
  end
end

What is wrong with it, step by step:

  1. No timeouts, so a slow provider holds a server thread for up to 60 seconds.
  2. A bare rescue turns a declined card, a timeout and a programming bug into the same nil.
  3. The caller gets nil and has no idea whether to apologise, retry or wait.
  4. No idempotency key, so a double click or a retry can charge twice.
  5. No distinction between "nothing happened" and "something may have happened".

Step one: add the key to the order. A migration adds a payment_idempotency_key column, and the model fills it once:

class Order < ApplicationRecord
  before_create { self.payment_idempotency_key ||= SecureRandom.uuid }
end

SecureRandom.uuid produces a random V4 UUID, the format Stripe suggests6. ||= only sets it if it is empty, so it never changes once written.

Step two: the rewritten gateway.

require "net/http"
require "json"

class PaymentGateway
  ENDPOINT = URI("https://api.payments.example/v1/charges")
  RETRYABLE = [Net::OpenTimeout, Net::ReadTimeout, Errno::ECONNRESET].freeze
  MAX_ATTEMPTS = 3
  BASE_WAIT = 0.5 # seconds
  MAX_WAIT = 8.0  # seconds

  def charge(order)
    attempt = 0
    begin
      attempt += 1
      interpret(send_charge(order))
    rescue *RETRYABLE
      raise FernhillTea::PaymentProviderUnavailable, "no answer after #{attempt} attempts" if attempt >= MAX_ATTEMPTS
      sleep(rand * [MAX_WAIT, BASE_WAIT * 2**(attempt - 1)].min)
      retry
    end
  end

  private

  def send_charge(order)
    Net::HTTP.start(ENDPOINT.host, ENDPOINT.port, use_ssl: true, open_timeout: 2, read_timeout: 8) do |http|
      request = Net::HTTP::Post.new(ENDPOINT)
      request["Authorization"] = "Bearer #{Rails.application.credentials.payments_key}"
      request["Idempotency-Key"] = order.payment_idempotency_key
      request.set_form_data(amount: order.total_pence, currency: "gbp", source: order.card_token)
      http.request(request)
    end
  end

  def interpret(response)
    case response
    when Net::HTTPSuccess
      JSON.parse(response.body).fetch("id")
    when Net::HTTPPaymentRequired
      raise FernhillTea::CardDeclined.new(JSON.parse(response.body).dig("error", "decline_code"))
    when Net::HTTPServerError
      raise FernhillTea::PaymentOutcomeUnknown, "provider returned #{response.code}"
    else
      raise FernhillTea::PaymentError, "unexpected status #{response.code}"
    end
  end
end

Walking through it:

  • The constants at the top write every limit down on purpose: which errors count as temporary, how many attempts, the base wait and the cap.
  • charge counts attempts. Inside begin it sends the request and interprets the answer.
  • rescue *RETRYABLE catches only the three temporary network errors. On the last attempt it raises PaymentProviderUnavailable, which the controller turns into "nothing has been charged, try again in a few minutes". Otherwise it sleeps for a random time below the doubling cap, the Full Jitter formula in one line, and retry runs the begin block again.
  • send_charge opens the connection with both timeouts set and sends the order's own idempotency key in the Idempotency-Key header, so every retry is the same payment.
  • interpret turns the HTTP status into business meaning. A success returns the charge id. Stripe, for one, answers with status 402 when the request was valid but the payment failed7, which is where a declined card lands, so it becomes CardDeclined with the bank's reason. A server error becomes PaymentOutcomeUnknown and is not retried with a new key, following the provider guidance7. Anything else is a PaymentError with the status in the message, so the error reporter shows it clearly.
  • A bug anywhere in this class, say a typo, is none of these classes. It travels up to the 500 page and the error reporter.

The declined card is never retried, because CardDeclined is not in RETRYABLE. The timeout is retried safely, because the key makes the retry harmless. The chapter on testing the unhappy path writes the tests for each of these branches first.

Tap or click to open full screen and move around

Stop calling a service that is down: the circuit breaker

Retries handle a bad minute. A circuit breaker handles a bad hour. The idea comes from Michael Nygard's book Release It!8 and Martin Fowler describes it plainly: wrap the remote call in an object that counts failures, and once they pass a threshold, the breaker "opens" and further calls fail at once without touching the remote service9. After a cooling off period it lets one call through to test the water. If that works, it closes again.

The point is not the remote service, it is your own shop. A failing call that returns at once leaves the server thread free for the next customer, and it lets you offer a fallback instead of a spinner.

Example: the courier's rate service

Fernhill Tea asks a courier for a live delivery price at checkout. When the courier's service is down, a flat £3.95 standard delivery is perfectly acceptable. Here is a small breaker:

class CircuitBreaker
  class OpenError < StandardError; end

  def initialize(threshold: 5, cool_off: 60)
    @threshold = threshold
    @cool_off = cool_off
    @failures = 0
    @opened_at = nil
  end

  def call
    raise OpenError, "circuit open" if open?
    result = yield
    @failures = 0
    result
  rescue Net::OpenTimeout, Net::ReadTimeout
    @failures += 1
    @opened_at = Time.now if @failures >= @threshold
    raise
  end

  private

  def open?
    return false unless @opened_at
    return true if Time.now - @opened_at < @cool_off
    @opened_at = nil
    @failures = @threshold - 1 # one more failure opens it again
    false
  end
end

And where it is used:

COURIER_BREAKER = CircuitBreaker.new(threshold: 5, cool_off: 60)

def delivery_price(basket)
  COURIER_BREAKER.call { CourierRates.quote(basket) }
rescue CircuitBreaker::OpenError, Net::OpenTimeout, Net::ReadTimeout
  FlatRate.standard # £3.95
end

Step by step: call refuses at once with OpenError while the breaker is open. Otherwise it runs the block, the real courier call, and resets the failure count on success. A timeout adds one failure and, at the fifth in a row, records the time the breaker opened, then raises the timeout again so the caller still knows. open? keeps the breaker open for 60 seconds, then lets the next call through with the count set one short of the threshold, so a single further failure opens it again. delivery_price falls back to the flat rate for both a fresh timeout and an open breaker.

This version counts in one process and is not thread safe. With several server processes, Priya would keep the count in the Rails cache and add a lock, or use a maintained gem.

Let background jobs retry for you

Work that does not have to happen while the customer waits belongs in a background job: the confirmation email, the invoice, the stock sync. Active Job, the Rails framework for jobs, has retries built in. retry_on catches the errors you name and runs the job again later, by default after 3 seconds and up to 5 attempts, and with wait: :polynomially_longer the waits grow to roughly 3, 18 and 83 seconds. discard_on drops a job for errors where trying again is pointless10.

Example: the order confirmation email

class OrderConfirmationJob < ApplicationJob
  queue_as :default

  retry_on Net::OpenTimeout, Net::ReadTimeout, wait: :polynomially_longer, attempts: 5
  discard_on ActiveJob::DeserializationError

  def perform(order)
    OrderMailer.confirmation(order).deliver_now
  end
end

If the email service times out, the job tries again after about 3 seconds, then about 18, then about 83, and so on up to five attempts. If it still fails, the error is passed up to the queue system underneath10 and the error reporter, and Priya sees it. ActiveJob::DeserializationError happens when the order the job refers to no longer exists, for example because it was deleted as a test order. No number of retries will bring it back, so the job is dropped. An email is safe to retry here because the worst case is a duplicate confirmation, which is annoying but harmless. A job that charges money would need the idempotency key from the payment section.

Error handling in JavaScript

The same principles apply in the browser and in Node.js. The traps are different.

try and catch with async and await

await turns a rejected promise into a thrown error, so a normal try and catch works. But fetch has a surprise: it only rejects when the request itself fails, for example on a network error. It does not reject when the server answers with an error status such as 404 or 50011. You must check response.ok yourself. And fetch has no timeout of its own, so you add one with AbortSignal.timeout, which aborts the request with a TimeoutError after the time you give it12.

Example: pausing a subscription

Fernhill Tea's customers can pause their tea subscription for a month. The React page calls this function:

export async function pauseSubscription(id) {
  let response
  try {
    response = await fetch(`/api/subscriptions/${id}/pause`, {
      method: 'POST',
      signal: AbortSignal.timeout(8000),
    })
  } catch (error) {
    if (error.name === 'TimeoutError') {
      throw new Error('The shop took too long to answer', { cause: error })
    }
    throw new Error('Could not reach the shop', { cause: error })
  }
  if (!response.ok) {
    throw new Error(`Pause failed with status ${response.status}`)
  }
  return response.json()
}

Line by line: the try covers only the network call. AbortSignal.timeout(8000) stops waiting after 8 seconds. The catch separates a timeout from other network failures and throws a new error with a clear message. After the try, the status check catches the case fetch lets through: the server answered, but with an error. Only a real success reaches response.json().

Unhandled promise rejections

A promise that rejects with nobody listening is an unhandled rejection. In the browser it fires an unhandledrejection event on window13. Since Node.js 15 the default is stricter: an unhandled rejection is raised as an uncaught exception and stops the process14. Either way the rule is the same. Every promise is awaited or given a catch, and a global listener is a safety net, not the plan.

Example: the pause button

// fragile: nobody waits for the promise, a failure goes nowhere
pauseButton.addEventListener('click', () => {
  pauseSubscription(subscriptionId)
})

// robust: the failure reaches the customer and the error monitor
pauseButton.addEventListener('click', async () => {
  try {
    await pauseSubscription(subscriptionId)
    showNotice('Your subscription is paused for one month.')
  } catch (error) {
    showNotice('The pause did not go through. Your subscription is unchanged, please try again.')
    errorMonitor.capture(error)
  }
})

// safety net for anything that still slips through
window.addEventListener('unhandledrejection', (event) => {
  errorMonitor.capture(event.reason)
})

In the fragile version a timeout leaves a button that did nothing. In the robust one the customer learns what state their subscription is in, and Priya gets the error with its cause. errorMonitor stands for whichever error monitoring library the shop uses.

Keep the original error with cause

When you catch an error and throw a clearer one, you used to lose the original. Error now takes an options object with cause, which keeps the original error attached to the new one, and browsers have supported it since 202115. In the pause example, the error monitor shows "The shop took too long to answer" and, underneath, the original TimeoutError. The message is for people, the cause is for debugging.

React error boundaries

In React, an error thrown while a component renders unmounts the whole tree unless something catches it. That something is an error boundary: a class component with static getDerivedStateFromError, which switches to a fallback, and usually componentDidCatch, which reports the error. Error boundaries do not catch errors in event handlers, in asynchronous code such as setTimeout, during server rendering, or in the boundary itself16. That is why the button above has its own try and catch.

Example: the subscription page

import { Component } from 'react'

export class ErrorBoundary extends Component {
  state = { hasError: false }

  static getDerivedStateFromError() {
    return { hasError: true }
  }

  componentDidCatch(error, info) {
    errorMonitor.capture(error, { componentStack: info.componentStack })
  }

  render() {
    if (this.state.hasError) return this.props.fallback
    return this.props.children
  }
}

And on the page:

<>
  <SubscriptionHeader customer={customer} />
  <ErrorBoundary fallback={<p>Your delivery dates could not load. Your deliveries are not affected.</p>}>
    <DeliverySchedule subscriptionId={subscription.id} />
  </ErrorBoundary>
  <PauseButton subscriptionId={subscription.id} />
</>

If DeliverySchedule meets a delivery with a missing date and throws while rendering, only that box is replaced by the fallback. The header and the pause button keep working, and the error reaches the monitor with the component stack that shows where it happened. Place boundaries around parts of the page that can fail on their own, not one around the whole app, which would only swap a blank screen for an apology.

Log with context, but without personal data

A good log line answers three questions: what happened, where, and to which record. It does not need to know who the customer is. The data protection principle of data minimisation says personal data must be "adequate, relevant and limited to what is necessary" for the purpose17. Logs and error reports are processing too, and they tend to be copied, kept for a long time and read by more people than the database. An order id lets Priya find everything she needs, with access controls around it. An email address in a log line is a leak waiting for a reason.

Rails helps. config.filter_parameters replaces sensitive request parameters with [FILTERED] in the logs, and a new Rails app filters :passw, :email, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn, :cvv and :cvc by default, matched partially18. The Rails error reporter, Rails.error, gives one interface for reporting errors to whatever service you use, and Rails already reports unhandled errors in requests and jobs through it19. Error monitoring services such as Sentry have their own switches: Sentry's send_default_pii controls whether user details are attached automatically, and its before_send hook lets you strip data before an event leaves your server20.

Example: one declined card, logged twice

The version that leaks:

Rails.logger.info("Payment failed for jane@example.com, card ending 4242, address 12 Park Row")

The version that helps:

Rails.logger.warn({
  event: "payment.declined",
  order_id: order.id,
  decline_code: error.decline_code,
  attempt: attempt,
  request_id: request.request_id
}.to_json)

Rails.error.report(error, handled: true, severity: :warning, context: { order_id: order.id })

The first line puts an email, part of a card number and an address into a file that is copied to backups and log tools. The second names the event, the order, the bank's reason, the attempt number and the request id, which links this line to every other line from the same request. Priya can find the customer through the order id if she has to, inside the admin area where access is controlled. The error report sends the same context to the monitoring service, marked as handled and as a warning, so it counts without waking anyone.

And in the Sentry setup:

Sentry.init do |config|
  config.dsn = Rails.application.credentials.sentry_dsn
  config.send_default_pii = false
end

send_default_pii = false stops the SDK from attaching user details to events automatically, so anything personal only gets there if Priya adds it deliberately, which she does not.

Alerts a person actually reads

An alert that fires every day trains everyone to ignore it, and then the one that matters is ignored too. Google's Site Reliability Engineering book puts it bluntly: every page should be actionable, and if a page merely merits a robotic response, it should not be a page21. So decide for each kind of error whether it needs a person now, a person tomorrow, or only a number on a dashboard.

Example: three alert rules for the tea shop

These thresholds are invented for the example:

  • Declined cards: no alert. Declines are normal customer life. A dashboard shows the daily rate so a sudden jump is visible.
  • PaymentProviderUnavailable: more than 5 in 10 minutes sends a message to Priya's phone. Customers cannot pay, and that is worth an interruption.
  • PaymentOutcomeUnknown: every single one creates a task for the next morning, because each one is an order that the reconciliation job could not finish on its own, and money may have moved.

Three rules, each with a clear action. If a rule fires and Priya does nothing, the rule is wrong and gets changed.

Where this sits in a test first workflow

Tap or click to open full screen and move around

Error handling is behaviour, so it is tested like any other behaviour, and the payment step sits on the shop's critical path, the chain that must never break. I work test first, so in my own projects each branch in the payment diagram above starts as a failing test, and every release passes a test gate before it goes live. The chapter on testing the unhappy path shows how to write those tests: a declined card, a timeout, the same request sent twice. For the wider method in Rails, the guide to TDD and BDD in Ruby on Rails is the place to start, and if your error handling crosses from one application to another, the article on testing APIs covers contracts between systems.

Example: the order of work for the payment rewrite

Priya does not rewrite the gateway in one go. She writes a failing test for a declined card and makes it pass, then one for a timeout followed by success, then three timeouts in a row, then a server error. Each step is small and proven, and if an AI assistant drafts any of the code, the tests decide whether it stays. That is the subject of the chapter on test driven development with AI.

Conclusion

Good error handling is a list of small, deliberate decisions written into code. Name the errors you expect and let the rest be loud. Give the business its own error classes, so every message to a customer says what happened and what to do. Put a written down timeout on every call that leaves the server. Retry in one place, few times, with growing random waits, and only what is safe to repeat, which for payments means an idempotency key stored on the order. Treat a provider's server error as "not known yet", never as "charge again". In JavaScript, check response.ok, never leave a promise unattended, and put error boundaries around the parts of a page that can fail on their own. Log ids and reasons, not people. Alert a person only when a person must act.

None of it is clever. All of it is the difference between a shop that has a bad minute and a shop that has a bad week.

If you want to know how your checkout behaves when the payment provider has a bad minute, book the free workshop: we walk through your payment path together, and the first two weeks of work are on me.

Sources

  1. 1.

    Ruby documentation, Exception handling (syntax/exceptions), ruby-lang.org, https://docs.ruby-lang.org/en/master/syntax/exceptions_rdoc.html

  2. 2.

    Rails Guides, Action Controller Advanced Topics: Handling errors and rescue_from, Ruby on Rails, https://guides.rubyonrails.org/action_controller_advanced_topics.html

  3. 3.

    Ruby documentation, class Net::HTTP (read_timeout, open_timeout, initial value 60), ruby-lang.org, https://docs.ruby-lang.org/en/master/Net/HTTP.html

  4. 4.

    Marc Brooker, Timeouts, retries, and backoff with jitter, Amazon Builders' Library, 2019, https://builder.aws.com/content/3EumjoZascWd1oZiEgL8ORlv3qE/timeouts-retries-and-backoff-with-jitter

  5. 5.

    Marc Brooker, Exponential backoff and jitter, AWS Architecture Blog, 4 March 2015, https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/

  6. 6.

    Stripe, API reference: Idempotent requests, Stripe Documentation, https://docs.stripe.com/api/idempotent_requests

  7. 7.

    Stripe, Advanced error handling, Stripe Documentation, https://docs.stripe.com/error-low-level

  8. 8.

    Michael T. Nygard, Release It! Design and Deploy Production Ready Software, second edition, Pragmatic Bookshelf, 2018, https://pragprog.com/titles/mnee2/release-it-second-edition/

  9. 9.

    Martin Fowler, CircuitBreaker, martinfowler.com, 6 March 2014, https://martinfowler.com/bliki/CircuitBreaker.html

  10. 10.

    Ruby on Rails API, ActiveJob::Exceptions::ClassMethods (retry_on, discard_on), Rails 8.1, https://api.rubyonrails.org/classes/ActiveJob/Exceptions/ClassMethods.html

  11. 11.

    MDN Web Docs, Window: fetch() method, Mozilla, https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch

  12. 12.

    MDN Web Docs, AbortSignal: timeout() static method, Mozilla, https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/timeout_static

  13. 13.

    MDN Web Docs, Window: unhandledrejection event, Mozilla, https://developer.mozilla.org/en-US/docs/Web/API/Window/unhandledrejection_event

  14. 14.

    Node.js documentation, Command line API: unhandled rejections mode (default changed to throw in v15.0.0), OpenJS Foundation, https://nodejs.org/api/cli.html

  15. 15.
  16. 16.

    React documentation, Component: catching rendering errors with an error boundary, Meta, https://react.dev/reference/react/Component

  17. 17.

    UK General Data Protection Regulation, Article 5(1)(c), legislation.gov.uk, https://www.legislation.gov.uk/eur/2016/679/article/5

  18. 18.

    Rails Guides, Configuring Rails Applications: config.filter_parameters, Ruby on Rails, https://guides.rubyonrails.org/configuring.html

  19. 19.

    Rails Guides, Error Reporting in Rails Applications, Ruby on Rails, https://guides.rubyonrails.org/error_reporting.html

  20. 20.

    Sentry, Scrubbing sensitive data (Sentry for Ruby), Sentry Documentation, https://docs.sentry.io/platforms/ruby/data-management/sensitive-data/

  21. 21.

    Rob Ewaschuk, Monitoring distributed systems, in Site Reliability Engineering, edited by Betsy Beyer and others, O'Reilly, 2016, https://sre.google/sre-book/monitoring-distributed-systems/