PgRest.Error.Translate (PgRest v0.2.0)

Copy Markdown View Source

Translates exceptions into PgRest.Error, mapping Postgres SQLSTATEs to HTTP statuses the way PostgREST does.

Message, details and hint come from Postgres. Any other exception becomes a generic 500 that never exposes the exception's text.

PT SQLSTATEs carry a custom HTTP status. PGRST SQLSTATEs decode MESSAGE JSON (code, message, optional details/hint) and DETAIL JSON (status and headers, optional status_text); malformed payloads return PGRST121.

Differences from PostgREST

DETAIL's status_text is validated but not sent as a custom HTTP reason phrase. PostgREST sends it; PgRest leaves the phrase to the host HTTP server.

Summary

Functions

from_exception/3 that also reports what was caught, for catch-alls. The log line carries the exception module (or :exit) and context only, never the message, SQL or parameters. Connection failures are logged as warnings, unexpected exceptions as errors, Postgres errors not at all.

Runs fun, turning a database or connection failure into {:error, %PgRest.Error{}} (translated for the request's role). Other exceptions propagate.

What kind of failure exception is: :database (Postgres or a PgRest.Error), :connection (driver or pool) or :internal (anything unexpected).

Types

role()

@type role() :: :anon | :authenticated

Functions

from_exception(exception, role, opts \\ [])

@spec from_exception(Exception.t() | atom(), role(), keyword()) :: PgRest.Error.t()

Builds a PgRest.Error from an exception.

Options

  • :scrub_details? - when true, drops details for SQLSTATEs 23502, 23503, 23505, 23514 and 23P01 (default false). Set it when the effective source is not the identity scope or a column allowlist narrows the resource, as Postgres does under row-level security.

from_exception_logged(exception, role, opts \\ [])

@spec from_exception_logged(Exception.t() | atom(), role(), keyword()) ::
  PgRest.Error.t()

from_exception/3 that also reports what was caught, for catch-alls. The log line carries the exception module (or :exit) and context only, never the message, SQL or parameters. Connection failures are logged as warnings, unexpected exceptions as errors, Postgres errors not at all.

guard_db(fun, role, opts \\ [])

@spec guard_db((-> result), role(), keyword()) :: result | {:error, PgRest.Error.t()}
when result: term()

Runs fun, turning a database or connection failure into {:error, %PgRest.Error{}} (translated for the request's role). Other exceptions propagate.

kind(arg1)

@spec kind(term()) :: :database | :connection | :internal

What kind of failure exception is: :database (Postgres or a PgRest.Error), :connection (driver or pool) or :internal (anything unexpected).