Skip to content

Problem

rn_forge.web.problem

RFC 9457 problem details and exception-to-problem mapping.

No RFC 9457 library is adopted: fastapi-problem 0.12.1 (checked 2026-09-23) emits no instance, sets its own type and title instead of about:blank and the status phrase, and has no exception-to-status registry.

BLANK_TYPE = 'about:blank' module-attribute

RFC 9457's prescribed type when there is no type URI to give.

GENERIC_SERVER_DETAIL = 'An unexpected error occurred.' module-attribute

What a 5xx detail says when the caller did not supply one. See :meth:ProblemRegistry.build.

NULL_FIELD_DETAIL = 'This field may not be null.' module-attribute

The detail of a validation error for a null on a non-nullable field, on every stack.

PROBLEM_MEDIA_TYPE = 'application/problem+json' module-attribute

The Content-Type every error response in this kit carries.

REQUIRED_FIELD_DETAIL = 'This field is required.' module-attribute

The detail of a validation error for a missing field, on every stack.

HasProblemExtensions

Bases: Protocol

An exception that contributes extension members to its own problem body.

:meth:ProblemRegistry.build merges the result beneath an explicit extensions= argument and only for a row below 500 — a 5xx body says nothing about the cause, so nothing an exception carries reaches the wire for one. An application that wants some of AppException.error_data on the wire implements this and chooses the members; error_data itself is never published automatically, since it routinely carries credentials and internal identifiers.

HasResponseHeaders

Bases: Protocol

An exception that contributes response headers to its own problem response.

:func:render_problem merges the result beneath an explicit headers= argument, so a caller's header always wins a collision.

ProblemDetail

Bases: WireModel

An RFC 9457 problem.

Extension members are flattened at the top level on the wire (RFC 9457 §3.2): the model allows extra members, and ProblemDetail(..., extensions={...}) merges a mapping in as extras. Core members win a collision with an extension of the same name.

extensions property

The extension members, as a fresh mapping.

as_body()

Return the wire body, extensions merged at the top level.

ProblemRegistry(*, type_base='', fallback=INTERNAL_ERROR)

Maps exception classes to problem types, resolving by MRO.

Parameters:

Name Type Description Default
type_base str

Prefix for the type URI. When empty (the default), the type is about:blank, which is what RFC 9457 prescribes when there is no type URI to give — a library must not invent a URI namespace. When set, type becomes type_base + slug.

''
fallback ProblemType

The row an unregistered exception resolves to.

INTERNAL_ERROR

Example::

registry = ProblemRegistry(type_base="https://errors.example.com/")
registry.register(OrderLocked, ProblemType("order-locked", 409, "Order Locked"))
body = registry.build(exc, instance="/orders/17").as_body()

fallback property

The row an unregistered exception resolves to.

build(exc, *, instance, detail=None, extensions=None, problem=None)

Build the problem body for exc.

Parameters:

Name Type Description Default
exc BaseException

The exception to describe.

required
instance str

A URI reference identifying this occurrence — in practice the request path.

required
detail str | None

Overrides the derived detail. Supply it to say something more useful than str(exc).

None
extensions Mapping[str, Any] | None

Extra members, flattened onto the wire body. Wins over a same-named member exc contributes via :class:HasProblemExtensions.

None
problem ProblemType | None

The row to build from instead of resolving one from exc — for a framework HTTP error, :meth:problem_for_status's.

None

Returns:

Type Description
ProblemDetail

The problem. When the status is 5xx and detail was not supplied,

ProblemDetail

the detail is :data:GENERIC_SERVER_DETAIL rather than

ProblemDetail

str(exc) — this is the one piece of policy in the module, and

ProblemDetail

it is the default because getting it wrong leaks internals.

ProblemDetail

When exc implements :class:HasProblemExtensions and the

ProblemDetail

resolved row's status is below 500, its problem_extensions()

ProblemDetail

are merged beneath extensions. Nothing is merged for a 5xx row —

ProblemDetail

a 5xx body says nothing about the cause, and that rule is not

ProblemDetail

reachable around.

ProblemDetail

title is row's title only when :attr:type_uri resolves to a

ProblemDetail

real URI (a type_base is configured, so the title describes

ProblemDetail

it). With about:blank, RFC 9457 §4.2.1 prescribes the HTTP

ProblemDetail

status phrase instead.

problem_for(exc)

Return the row for exc, walking its MRO before falling back.

The MRO walk is what makes an adapter subclass resolve to its base class's row without anyone remembering to register it.

problem_for_status(status)

Return the row for a bare HTTP status that carries no exception type.

A framework raises HTTP errors no application registered — a routing 404, a 405. The row is the first registered row with that status, so a framework 404 and a LookupError produce the same body. With no such row it is derived from the IANA reason phrase (405 → method-not-allowed / Method Not Allowed); a status with no reason phrase resolves to the fallback.

register(exc_type, problem)

Register problem for exc_type, returning self for chaining.

register_hierarchy(base, *, code_attr='code', status_attr='status_code')

Register a row for base and every subclass, returning self.

Each class gets ProblemType(code, status, phrase): its code_attr is the slug, its status_attr the HTTP status, and the title is that status's IANA reason phrase. The attributes are read with getattr, so a subclass inherits them or overrides them. Classes are walked depth first, base first, in __subclasses__() order, each once; only classes already imported are seen.

Parameters:

Name Type Description Default
base type[Exception]

The root of the exception hierarchy.

required
code_attr str

The class attribute holding the slug.

'code'
status_attr str

The class attribute holding the HTTP status.

'status_code'

Raises:

Type Description
TypeError

A class in the hierarchy has no code_attr or no status_attr; the message names the class and the attribute.

ValueError

A class's status has no IANA reason phrase.

Example::

class AppError(Exception):
    code = "app-error"
    status_code = 500

class OrderLocked(AppError):
    code = "order-locked"
    status_code = 409

registry.register_hierarchy(AppError)

rows()

Return a read-only view of the registered rows, in registration order.

A framework adapter needs the registered exception types — Starlette dispatches a handler per class — and an OpenAPI document needs the statuses they map to.

type_uri(problem)

Return the type member for problem.

ProblemResponse(problem, headers) dataclass

A rendered problem response, ready for a framework to send.

The body is :attr:problem's wire form and the Content-Type is always :data:PROBLEM_MEDIA_TYPE.

body property

The JSON body, extensions flattened (:meth:ProblemDetail.as_body).

status property

The HTTP status.

ProblemType(slug, status, title) dataclass

A registry row: the slug, status and title a class of failure maps to.

default_registry(*, type_base='')

Return a fresh registry carrying this package's exceptions.

A factory, never a shared module-level singleton: a consumer that mutated a shared registry would change every other consumer's error bodies.

Parameters:

Name Type Description Default
type_base str

Forwarded to :class:ProblemRegistry.

''

field_error(path, detail)

Return one validation-error entry: {"pointer": ..., "detail": ...}.

The shape is RFC 9457 §3's validation example; a framework binding builds one per field message and puts the list under the errors extension.

Parameters:

Name Type Description Default
path Iterable[object]

The field's location, outermost first. Segments are escaped per RFC 6901 §3; an empty path is the document root ("").

required
detail str

The human-readable message for that field.

required

Example::

field_error(("items", 1, "qty"), "must be > 0")
# {"pointer": "/items/1/qty", "detail": "must be > 0"}

problem_from_body(status, body)

Parse an upstream application/problem+json body back into a problem.

Missing type defaults to about:blank, missing status falls back to status, and unknown members become extensions.

Parameters:

Name Type Description Default
status int

The HTTP status of the response the body came from.

required
body Mapping[str, Any]

The decoded JSON object.

required

Returns:

Type Description
ProblemDetail

The parsed problem.

render_problem(registry, exc, *, instance, problem=None, detail=None, extensions=None, headers=None, realm=None)

Render exc as a complete problem response: body and headers.

On top of :meth:ProblemRegistry.build:

  • the current span's trace id is the traceId extension (null when no span is recording);
  • a 401 carries :data:~rn_forge.web.auth.AUTH_FAILED_DETAIL as its detail, whatever detail says, and a WWW-Authenticate challenge unless headers already carries one or exc is an :class:~rn_forge.web.exceptions.AuthenticationFailed whose challenge is false;
  • a csrf-failed problem carries :data:~rn_forge.web.auth.CSRF_FAILED_DETAIL as its detail, whatever detail says;
  • when exc implements :class:HasResponseHeaders, its headers are merged beneath headers, so an explicit headers entry wins.

Parameters:

Name Type Description Default
registry ProblemRegistry

The rows to render with.

required
exc BaseException

The exception being rendered.

required
instance str

The instance member — in practice the request path.

required
problem ProblemType | None

The row to use instead of resolving one from exc.

None
detail str | None

Overrides the derived detail.

None
extensions Mapping[str, Any] | None

Extra members, flattened onto the body.

None
headers Mapping[str, str] | None

Response headers to carry, e.g. a framework-built challenge.

None
realm str | None

The realm of the challenge added to a 401.

None

Returns:

Type Description
ProblemResponse

The response. Logging a 5xx is the caller's job.

unmapped_exceptions(registry, *bases)

Return every subclass of bases that resolves to registry's fallback.

Recursively walks __subclasses__() from each base. An application calls this from a test or a readiness check to prove its exception table is total — a domain error that resolves to the fallback becomes a 500 with nothing to catch it.

Parameters:

Name Type Description Default
registry ProblemRegistry

The registry to check resolution against.

required
bases type[BaseException]

The exception base classes to walk subclasses of.

()

Returns:

Type Description
list[type[BaseException]]

The unmapped subclasses, sorted by qualified name.