/sorah-guides:rails-problemfrom sorah-guides
Designs and reviews RFC 9457 error handling in Rails APIs using the `problem` gem. Covers error classes, rescue_from, exceptions app, i18n titles, and machine-readable detail.
Ships in sorah-guides. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
problemConventions for answering errors from a Rails API as RFC 9457 problem documents with the problem gem. Project-specific conventions (CLAUDE.md, docs/) always take priority.
problem works on its own: error classes declare type, status and title with its DSL, and nothing else is needed. An app whose schema lives in .proto files can instead take those from a protobuf enum through protobufable; the sections below cover both, and /sorah-guides:rails-protobuf covers the enum catalogue and answering problems over Connect RPC. Application examples come from ruby-no-kai/sponsor-app, which uses the protobuf form.
An error is a class. Its type, status and title belong to the class and are declared once; only detail (and machine-readable extras) vary per occurrence. A controller concern renders every such class, and an exceptions app renders whatever escapes before a controller runs, so every failure a client sees has one shape.
type. A title can be reworded freely; a type is a published identifier and is append-only.detail is prose for a person, specific to the occurrence. Anything a client acts on goes in an extension member, never parsed out of detail.One base class carries the mixin; every error is a subclass that declares what differs. Keep them together in app/models/errors.rb (a module Errors), with a one-line doc comment per class saying when it is raised.
Without protobuf, the base includes Problem::Detailable (or Problem::I18nable for translated titles, which brings Detailable with it), and each class declares its members with the DSL:
# app/models/errors.rb
module Errors
# An error the API answers as a problem.
class ApiError < StandardError
include Problem::Detailable
end
# The resource the request names does not exist.
class NotFound < ApiError
type "not-found"
status 404
title "Not Found"
end
# The resource is not in a state that allows the request.
class FailedPrecondition < ApiError
type "failed-precondition"
status 412
title "Failed Precondition"
end
end
type is a slug resolved against config.problem.type_prefix; without a type the document says about:blank.class Orders::AlreadyShipped < Errors::FailedPrecondition with its own type and title keeps the 412.title keeps it even under Problem::I18nable, so titles can move to locale files gradually.With protobufable, the base includes Protobufable::Problem::Typeable and points at an enum whose values carry the uri and http_status; each class names a value instead of declaring members. sponsor-app:
# app/models/errors.rb (sponsor-app)
module Errors
# An error the API answers as a problem, typed by a value of the ProblemType enum in
# proto/rubykaigi/sponsor_app/problem.proto.
class ApiError < StandardError
include Protobufable::Problem::Typeable
#: () -> String
def self.problem_type_enum = 'rubykaigi.sponsor_app.ProblemType'
#: () -> String
def self.problem_type_annotation = 'rubykaigi.sponsor_app.problem_type'
end
# The resource the request names does not exist.
class NotFound < ApiError
problem_type :PROBLEM_TYPE_NOT_FOUND
end
end
Typeable includes Problem::I18nable, and so Problem::Detailable, so everything below (rendering, hooks, the exceptions app, extension members) applies unchanged. Titles come from locale files, keyed by the uri.
detail: that names the specific thing: raise Errors::NotFound.new(detail: "No conference has the slug #{slug.inspect}."). Never put internals (SQL, stack details, other tenants' data) in detail; it goes to the client.detail. A subclass that declares nothing renders exactly as its parent, which is the tool for hiding a distinction: when a caller must not tell two failures apart, make an empty subclass instead of a new type.The code that detects a failure raises the problem. A model or service raises a detailable class named for what went wrong, and the controller does nothing: the error already carries its type, status and title wherever it is raised, and Problem::Rescuable renders it.
# Bad - the service raises a plain error, and the action rescues everything to re-raise a
# class named after an HTTP status
class Orders::Cancel
def call(order)
raise "already shipped" if order.shipped?
# ...
end
end
def cancel
Orders::Cancel.new.call(order)
rescue => e
raise Errors::BadRequest.new(detail: e.message)
end
# Good - the service raises the problem itself, and the action has no rescue
module Errors
# The order has left the warehouse and can no longer be cancelled.
class OrderAlreadyShipped < FailedPrecondition
type "order-already-shipped"
title "Order Already Shipped"
end
end
class Orders::Cancel
def call(order)
raise Errors::OrderAlreadyShipped.new(detail: "Order #{order.id} shipped at #{order.shipped_at.iso8601}.") if order.shipped?
# ...
end
end
def cancel
Orders::Cancel.new.call(order)
head :no_content
end
Errors::OrderAlreadyShipped), not for its status. Subclass the closest general class so it inherits the status. The status-named general set (NotFound, Forbidden, FailedPrecondition) is for raising directly only when no client will branch on the distinction.type clients dispatch on, turns bugs into 4xx answers, and makes the controller know every failure below it.rescue StandardError (or a bare rescue) to answer 500. An unexpected error propagates, and Problem::Rescuable and the exceptions app already answer it as a 500 and report it.ActiveRecord::RecordNotFound, RecordInvalid) in the base controller, a gem's or client's errors at the service boundary that calls it. That boundary wraps every failure unconditionally into a problem class named for what failed there, with cause: set (see /sorah-guides:coding).Include Problem::Rescuable once in the API's base controller. It rescues every class that mixed in Problem::Detailable, so do not add a rescue_from per error class; make the error class detailable instead.
Convert framework exceptions into problems at one place in the base controller, and render them with render_problem_detailable. sponsor-app turns ActiveRecord::RecordInvalid from save! into its own InvalidRecord problem:
rescue_from ActiveRecord::RecordInvalid, with: :render_invalid_record
private def render_invalid_record(error)
# ...
render_problem_detailable(Errors::InvalidRecord.new(record: error.record, ...))
end
Actions then call save!/update! and let validation failures propagate, instead of branching on save and rendering errors by hand.
Hooks on a controller including Problem::Rescuable, overridden as private def:
| hook | use for |
|---|---|
problem_for(error) | Adding request-derived members, such as instance |
around_problem_render(&) | Re-establishing the locale (or other per-request state) while rendering |
report_problem?(error, problem) | What counts as reportable (default: status >= 500) |
report_problem(error, problem) | Where reports go |
render_problem(problem, error) | Answering in another shape entirely |
sponsor-app reports every problem to Sentry, as rescue_from swallows it before Sentry's middleware sees it:
# rescue_from swallows the problem before Sentry's middleware sees it, and Sentry does not
# subscribe to the Rails error reporter here.
private def report_problem(error, problem)
super
Sentry.capture_exception(error)
end
Configure in config/initializers/problem.rb:
Rails.application.configure do
# Problem types are identifiers rather than links, so every environment publishes the production
# host's.
config.problem.type_prefix = 'https://sponsorships.rubykaigi.org/problems/'
config.exceptions_app = Problem::ExceptionsApp.new(ActionDispatch::PublicExceptions.new(Rails.public_path))
end
type_prefix is the same in every environment. A type is an identifier, not a link that must resolve per host.Problem::ExceptionsApp answers routing errors, unreadable bodies and middleware failures as problems with the status text instead of the exception message, while browsers keep the static error pages. Subclass it when escaped errors need another shape, as sponsor-app's ConnectExceptions does for Connect clients.action_dispatch.show_exceptions = :all around the example; sponsor-app tags them :escaping_exceptions (spec/support/connect_helper.rb).title is the only member written for a human, so it is the one to translate. Include Problem::I18nable in the base class; titles are keyed by type with dashes replaced, under problem_details.titles in config/locales/*.yml. Wrap rendering in the request's locale:
private def around_problem_render(&) = I18n.with_locale(negotiated_locale, &)
The wrapper is required: Rails has already unwound around_action by the time an error renders. Classes sharing a type share a title too, so localization cannot leak a hidden distinction.
RFC 9457 has no member for field errors. Return extension members from the error:
def problem_extensions = super.merge(decline_code: @decline_code)
Always super.merge, so mixins contributing members compose. Problem::RetryAfter (retry_after:) sends Retry-After and a retry_after member.
Without protobuf, field errors from a failed save become an extension member of the invalid-record problem:
# The record the request would save fails validation.
class InvalidRecord < ApiError
type "invalid-record"
status 422
title "Invalid Record"
def initialize(record:)
@record = record
super(detail: record.errors.full_messages.join("; "))
end
def problem_extensions
super.merge(errors: @record.errors.map { {field: it.attribute.to_s, message: it.message, reason: it.type.to_s} })
end
end
With protobufable, Protobufable::Problem::Information carries packed google.rpc.* messages such as BadRequest in information; sponsor-app's Errors::InvalidRecord maps each model error to a FieldViolation on the request's Input field (see /sorah-guides:rails-protobuf).
Content-Type: application/problem+json, and type, not the title or detail wording.Problem; an app with its own Problem model has a Zeitwerk conflict to resolve.application/problem+xml is not implemented.What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
23 skills in this plugin
/codingThis skill should be used when writing or reviewing code in any language. Provides language-agnostic coding conventions for code quality, comments, error handling, and formatting. Project-specific conventions always take priority./commit-styleThis skill should be used when writing git commit messages, creating git commits, composing pull request titles and descriptions, or when the user asks to "commit", "git commit", "write commit message", "pull request", or "PR description". Provides conventions for subject lines, prefix patterns, body content, and verb choices./dsql-on-railsThis skill should be used when building, extending, or testing a Rails app on Amazon Aurora DSQL, or when moving a Rails app onto DSQL. Use it when writing a transaction, a uniqueness check, a schema change, a spec, a rake task, or CI for such an app, even if the user only says "add a model" or "fix this flaky spec" in such an app. Signs include `aws-sdk-dsql`, `pg-aws_rds_iam`, `aws_rds_iam_auth_token_generator`, a `*.dsql.<region>.on.aws` host, `ActiveRecord::SerializationFailure` with `OC000`/`OC001`, `retryable_transaction`, `non_idempotent_transaction`, `create index async`, `script/pdsql`, or the user mentioning "DSQL", "Aurora DSQL", or "OCC". Provides connection settings and adapter patches, OCC-aware transactions, schema constraints with psqldef, roles, per-developer schemas, RSpec setup, and CI against real clusters. Project-specific conventions always take priority.npx claudepluginhub sorah/config --plugin sorah-guidesOther plugins' skills for the same job