skip to content

In an Active Job class, when an exception matches several retry_on, discard_on or rescue_from declarations, which one handles it, and why does order matter?

level: middleimportance: should knowfreq 32%

answer

  1. all three are rescue_from underneath
  2. last declared is checked first
  3. subclass rules before ApplicationJob's
  4. first is_a? match wins, then cause
  5. a swallowing handler means success

basics

~20 s

retry_on and discard_on are built on rescue_from, and Active Job checks handlers from the last declared upward, the job's own before ApplicationJob's. The first whose class matches wins, so a broad rule declared after a narrow one hides it.

solid answer

~40 s

`retry_on` and `discard_on` each register a `rescue_from` handler, so all three share one list. When `perform` raises, Active Job walks that list **from the last declaration to the first**; a subclass's rules come after `ApplicationJob`'s in the list, so they are checked before the inherited ones. The first handler whose class matches by `is_a?` handles the error, and no other runs. So `discard_on LabelClient::InvalidAddress` followed by `retry_on StandardError` retries invalid addresses, because the later, broader rule is found first; put specific rules **last**. If nothing matches the exception, Active Job tries the same lookup on its `cause`. A plain `rescue_from` block that does not re-raise counts as handling: the job finishes as successful, with no retry and nothing kept as failed, unless the block calls `retry_job` or raises.

code

ruby · 11 lines
ruby
class ShippingLabelJob < ApplicationJob
  # Broad rule first...
  retry_on LabelClient::Error, wait: :polynomially_longer, attempts: 5
  # ...specific rules after it, so they are checked first
  discard_on LabelClient::InvalidAddress
  retry_on LabelClient::RateLimited, wait: 1.minute, attempts: 10

  def perform(order)
    LabelPurchase.new(order).call
  end
end

go deeper

for a junior

Remember that retry_on, discard_on and rescue_from all catch exceptions in a job, and that only one of them handles any given error.

for a middle

Explain the lookup: last declared first, subclass before ApplicationJob, first is_a? match, then the cause, and what a swallowing rescue_from does to the outcome.

for a senior

Review job classes for shadowed rules and silent rescue_from blocks, and structure error hierarchies so retry and discard rules stay unambiguous.

for a principal

Standardise how jobs declare error policy across teams, so base-class defaults and per-job overrides compose predictably instead of shadowing each other.

## One list of handlers Active Job includes `ActiveSupport::Rescuable`, the same module behind `rescue_from` in controllers. In a job class, `retry_on` and `discard_on` are thin wrappers: each calls `rescue_from` with a block that retries or discards. So whatever mix of the three a job declares, there is **one ordered list of handlers**, and the class's position in its hierarchy adds the parent's entries to it. ## How the handler is chosen When `perform` raises, `perform_now` passes the exception to `rescue_with_handler`, which: 1. walks the list **in reverse**: the most recently declared handler first, up to the earliest; 2. includes inherited handlers after the class's own, because a subclass appends its declarations to the list it inherits from `ApplicationJob`; 3. picks the **first** entry whose class the exception `is_a?` (string class names are resolved first); 4. if no entry matches, repeats the search for `exception.cause`, so a wrapped low-level error can still hit a rule; 5. if still nothing matches, gives up: `after_discard` callbacks run and the exception propagates to the backend. Only one handler ever runs for one exception. ## A worked example ```ruby class ApplicationJob < ActiveJob::Base retry_on StandardError, attempts: 3 end class ShippingLabelJob < ApplicationJob retry_on Net::ReadTimeout, wait: :polynomially_longer, attempts: 8 discard_on LabelClient::InvalidAddress rescue_from LabelClient::RateLimited do |error| retry_job wait: 1.minute end end ``` | Exception raised | Handler that wins | Why | |---|---|---| | `LabelClient::RateLimited` | the `rescue_from` block | declared last in the subclass, checked first | | `LabelClient::InvalidAddress` | `discard_on` | the subclass's rule beats the inherited `StandardError` rule | | `Net::ReadTimeout` | `retry_on ..., attempts: 8` | checked before the inherited rule | | `NoMethodError` (a bug) | `ApplicationJob`'s `retry_on StandardError` | only the inherited rule matches | Now reverse the order inside `ShippingLabelJob` by adding `retry_on StandardError, attempts: 3` as its **last** line. Every one of the label errors is a `StandardError`, so that new last line is found first and catches them all: invalid addresses get retried three times, rate limits lose their one-minute wait. The specific rules above it never run. ## rescue_from in a job `rescue_from` is still useful on its own, for logic the two macros do not cover: - calling `retry_job` with a computed `wait:`, a different `queue:` or `priority:`; - recording the failure on a model and finishing quietly; - translating one error into another and raising that. The handler can be a block or a method: `rescue_from LabelClient::RateLimited, with: :back_off` calls the job's `back_off` instance method, passing the exception if the method takes an argument. Either way it runs inside the job instance, so it can read `arguments`, `executions` and `job_id`. What matters is the **outcome of the block**: - **returns normally**: the error is handled and the job counts as **successful**; on Solid Queue it is marked finished and later cleared, with no failed execution; - **calls `retry_job`**: a new attempt is scheduled and this run counts as handled; nothing counts the attempts for you, so cap them yourself, for example with `executions`; - **raises** (re-raising the error or a new one): the job fails as if no handler had matched it. The classic slip is a reporting block, `rescue_from(StandardError) { |e| Rails.logger.error(e) }`, that silently turns every failure into a success. ## Checking what a class will do The handler list is inspectable, which helps in code review and in tests: ```ruby ShippingLabelJob.rescue_handlers.map(&:first) # => ["StandardError", "Net::ReadTimeout", # "LabelClient::InvalidAddress", "LabelClient::RateLimited"] ``` Read that array **from the end**: that is the order Active Job tries. Anything broad near the end shadows everything before it that it covers. A short test that raises each expected error inside the job and asserts the outcome (retried, discarded, failed) catches a shadowing mistake the moment someone appends a rule. ## Guidelines - Put broad rules in `ApplicationJob` or **at the top** of a class, and specific ones below them. - Avoid a class-level `retry_on StandardError` below specific rules; it shadows all of them. - Make catch-all `rescue_from` blocks re-raise unless swallowing is the intent. - When an API client wraps errors, give your own exception a `cause` or rely on Ruby setting it, so rules written for the low-level class still match.

  • The API client raises LabelClient::Error from a rescue of Net::ReadTimeout. Will retry_on Net::ReadTimeout catch it?
    Only if nothing matches `LabelClient::Error` itself. Raising inside a `rescue` sets the new exception's `cause` to the timeout, and Active Job retries the handler lookup on the `cause` when the outer exception matches nothing. If any rule matches `LabelClient::Error` (or a broad `StandardError` rule exists), that rule wins first.
  • A rescue_from block calls retry_job for rate limits. What stops it retrying forever?
    Nothing, unless you add a cap. `retry_on` counts attempts for you; a hand-written handler does not. Use the job's `executions` counter, which Active Job increments on every run and keeps across `retry_job`: call `retry_job wait: 1.minute` while `executions` is below your limit, and `raise error` once it is reached so the job fails visibly.

  • Saying the most specific exception class always wins, whatever the order
  • Believing every matching retry_on and discard_on rule runs in turn
  • Expecting a rescue_from block that only logs to leave the job failed
  • Claiming ApplicationJob's handlers are checked before the subclass's own
  • Adding retry_on StandardError at the bottom of a job as a safe default