Skip to main content

API error architecture

The record is from 2026-10-21, updated on 2026-10-27.

This page records why jodapp-api error handling is changing.

  • The parent effort is jod-app/roadmap#92, "2026 Q4 - API Error Architecture".
  • jod-app/docs#171, "API Error Architecture - Initial", asks for this page.
  • It lists every option we weighed, and the temporary ruling.
  • It came out of the Billing interface design, Phase 1 of jod-app/roadmap#87.
  • The code was read on feature/backend-billing-phase-3 at e545b6089 and 14baad523.

Words​

WordMeaning
An entry pointA way into the code: a controller action, a Sidekiq job, a rake task or the console.
The class Errors::BaseErrorThe parent of every error in app/shared/errors/, with title, messages, code, server, status and status_name.
The class Errors::ValidationErrorThe 422 a manager raises from the errors of its validator.
The class Errors::UnprocessableContentErrorThe 422 a manager raises for a business rule, per app/domains/AGENTS.md rule 3.
A managerThe class that owns one endpoint flow and its transaction, such as Ads::Campaigns::TeamSubmitManager.
A domain serviceA class another domain calls, such as the planned Billing::SpendService.
The class Billing::SpendValidatorThe planned public Billing check that a product validator runs before the transaction and merges with errors.merge!.
The guardThe second credit check inside a write method, under lock('FOR UPDATE') on the balance row.
A business rejectionA failure where a rule said no, such as not enough credits.
An invariant violationA failure that means the data is wrong, such as a ledger that disagrees with its balance row.

Why we are looking at this now​

Errors::BaseError was written when every entry point was a controller, and that is no longer true.

  • Billing used to serve only its own Team Portal endpoints.
  • Now Billing::SpendService is called by product managers inside requests and by product jobs with no request.
    • Rake tasks and the console will call it too.
  • One object carries the user words and the HTTP status.
    • So a job or a console holds a status it can never send.
  • Ali (CTO) requires that every Billing error reaches Sentry.
    • Nothing in Billing sets skip_sentry.

The model we agreed​

Each failure has two owners: the domain says what went wrong, and the entry point reports it.

  • The domain that knows what happened owns the error class, its words and its code.
  • The entry point decides how to report the error.
    • A controller action answers with JSON and an HTTP status.
    • A Sidekiq job rolls back one record, reports it to Sentry, and moves to the next record.
    • A rake task or the Rails console prints the error class and its message.
Entry pointWho catchesWhat handling means there
ControllerApplicationController rescue_fromJSON with a status, Sentry by policy
Sidekiq jobOne rescue per recordRoll back the record, report with the record id, move on
Rake task or consoleNobodyPrint the class and message, Sentry through the Rails integration

Three kinds of failure, and only one gets a named class.

KindExample in BillingWho acts on itShape
A business rule said noNot enough creditsA caller, by classA named class under one base class per domain
An invariant brokeLedger and balance disagree, consume with no reserve entry, a company with no billing accountNobody, it is a bugA plain error, never a Billing::Error
The write was called wrongNo open transaction, wrong argument typeNobody, it is a bugA plain error

Boundary rule: only an entry point catches an error.

  • A domain raises its own errors, and lets the errors of another domain pass through.
  • A product manager never rescues a Billing error to translate it.
  • Errors::ValidationError stays the manager's raise, because a request failing validation is request-shaped by nature.

Every option we considered, so nobody weighs them again​

For what Billing::SpendService raises when the balance is too low under the lock​

ShapeWhat it isVerdictWhy
1The shared Errors::UnprocessableContentError, no new class, code: 'insufficient_credits' added later if the web needs itRuled, then reopened the same dayWhat a public interface raises is part of its contract, and a job would rescue an HTTP-named error
2A pure Billing::InsufficientCreditsError < StandardError, and every product manager rescues it and re-raises the shared 422RejectedA rescue and re-raise in every manager that carries no decision
2bThe pure error, and one translation at the HTTP edge in ApplicationControllerTemporarily ruled, then generalised into option B belowThe textbook shape, as Rails maps ActiveRecord::RecordNotFound to 404 in rescue_responses
3Billing::InsufficientCreditsError < Errors::UnprocessableContentError with code: 'insufficient_credits', Imam's proposal plus the codeCodex chose it on run 1; it is the bridge belowRides the existing renderer, but Billing inherits HTTP

For the parent class of Billing::Error​

OptionWhat it isVerdictWhy
ABilling::Error < Errors::UnprocessableContentError, no shared-error changeThe bridge until B landsBilling names HTTP, and a job holds a status it cannot send
BErrors::BaseError drops status and status_name, and ApplicationController holds one class-to-status table; Billing::Error < Errors::BaseErrorTemporarily ruled 2026-10-21One hierarchy, no copy, HTTP only in the controller, every raise site unchanged
CA new Errors::DomainError < StandardError beside Errors::BaseError, with the same words fields minus statusRejectedAli saw it is a copy of BaseError without the status, so two parallel hierarchies

Other choices made on the way​

ChoiceRulingWhy
The pre-checkBilling::SpendValidator, run by the product validator with values, merged with errors.merge!Billing owns the rule and the words; the dependency points one way
validates_with Billing::SpendValidator, ...RejectedBilling would call methods on a product object by name, with no sig
available_units as the public pre-checkReplaced by the validatorEvery product repeated a rescue and the words
The error key<instrument>_credits, such as placement_creditsOne key for the validator and the guard, and the web branches on this key
The wire codeinsufficient_credits, set explicitly, never the Ruby class nameA Ruby rename must not break a web constant
Billing::Error base classYes, one per domainThe entry point and a job catch "any Billing rejection" in one line; invariant violations never inherit it
skip_sentry in BillingNeverA guard failure is a race or a skipped validator, and both must be seen
Default status for an unmapped Errors::BaseError under B500, not 422An unmapped error is a bug

What Codex said​

Three runs, gpt-6-astra, effort xhigh, read-only, on 2026-10-21.

  1. Run 1, shapes 1 to 3: chose Shape 3.
    • It named the HTTP inheritance as a real coupling, accepted because the renderer exists.
    • One class only, no base class.
    • The web cannot see every shortage through code, because the normal path returns Errors::ValidationError.
  2. Run 2 gave no answer.
  3. Run 3, options A to C: chose B.
    • Nothing outside ApplicationController#base_error reads error.status or status_name, in app/, config/ or test/.
    • Ten files change: BaseError, ApplicationController, eight subclasses, TooManyRequestsError at 429 included.
    • Remove the status readers' sigs too, make request nullable, drop or initialize level, and pass a string to super.
    • Keep messages as a Hash of Symbol to Array of String on the domain error.
    • In before_send, classify by class before the skip_sentry rule, and exempt every Billing::Error.
    • Production config/sentry.yml has sample_rate: 0.5, and sampling runs before before_send, so half of all errors never reach Sentry today.

The temporary ruling, 2026-10-21​

Option B, with the plan below, pending one investigation.

  • The investigation: whether B changes anything the frontend error framework reads.
    • The JSON shape stays identical, so the expected answer is no, and it must be checked.
    • Check jodapp-web app/api/ky-client.js, app/utils/error-utils.js, app/components/error-display/api-error-view.jsx, and every error.status, error.code and status_name read.

The plan​

PRWhereWhatSize
1jodapp-api mainBaseError drops the status and its sigs, fixes request, level and super; eight subclasses drop @status_name; ApplicationController gets STATUS_BY_ERROR_CLASS and an ancestor lookup with 500 as default; one test per mapped classTen files, about a hundred lines
2jodapp-api mainconfig/sentry.yml error sample_rate to 1.0 in production; before_send classifies by class before skip_sentryTwo files
3jodapp-api main, after the Billing interface mergesBilling::Error inherits Errors::BaseError; one table line Billing::Error => :unprocessable_contentTwo lines
  • One convention page in docs/90-99-engineering-meta/96-conventions/, and four lines in app/domains/AGENTS.md rule 3.
  • The other four services that raise shared errors today move when someone next changes their file.

The bridge: what Imam builds now without waiting for B​

The Billing interface builds Shape 3, in jodapp-api PR #2224, and B later changes one line.

  • app/domains/billing/error.rb with Billing::Error < Errors::UnprocessableContentError, and app/domains/billing/insufficient_credits_error.rb with Billing::InsufficientCreditsError < Billing::Error.
  • It sets code: 'insufficient_credits' explicitly, and Billing's words under <instrument>_credits.
  • SpendService raises it under the lock, and no manager rescues it.
  • A job rescues Billing::Error first, then StandardError.
  • When B lands, the parent line becomes < Errors::BaseError and the table gets one line.
    • No raise site, rescue site, test or web constant changes.

Open items​

  • The frontend investigation above.
  • Who builds PR 1 and PR 2: an Opus engineer agent from a brief, or Imam.
  • Decided 2026-10-27: a company without an account is not an allowed state, so Billing::NoBillingAccountError does not exist.
    • A missing account raises Errors::InternalServerError, which Sentry reports as an error.
    • Reason: every company is created with its own account, and jodapp-api PR #2183 created the account of every older company.
  • The Billing page overview/interface.md and Billing D18 are on docs PR #165.
    • Since 2026-10-27, both name Billing::Error and Billing::InsufficientCreditsError as the current classes.