feat: parse the server error envelope onto the base exception classes
Why
Part of the error enrichment that was included in 1.10.0 the overall epic aims to allow the SDK to raise more specific errors when there are problems such as node not found instead of the generic GraphQLError
When Infrahub rejects a request, the SDK throws away almost everything the server said about why. A caller who needs to react to a specific failure has only the message text to go on, so the only way to branch on "this was a uniqueness violation" rather than "something failed" is to string-match prose that is free to change between releases. The SDK does this to itself too, matching the literal "Expired Signature" to decide whether a 401 is worth a silent token refresh.
Goal: carry the server's error envelope onto the exception, so exc.code is the thing you branch on.
Non-goals: this is issue 1 of the four in the spec's PR split. It deliberately does not add generated per-code bindings (issue 3), re-root the not-found classes or touch the CLI error ladder (issue 2), or change any error message. No class anyone catches changes shape.
Part of IFC-3034 / IHS-293.
What changed
Behavioural:
AuthenticationErrorandGraphQLErrornow carrycode,http_status,extensions, anderrorsfrom the server's response, via a new sharedApiErrorbase. Callers can branch on the catalogue code instead of the message.- The silent token refresh is decided by
TOKEN_EXPIREDin the envelope, with the legacy"Expired Signature"string kept only for servers that predate the catalogue. That literal now appears once in the SDK, down from twice. - Fixes a crash: a 401 whose body was valid JSON but not an object (a bare array, string, or
null, as a proxy or gateway can return) raisedAttributeErrorout of the client. It now surfaces asAuthenticationErrorlike every other unreadable 401. - Rejected file uploads now raise
AuthenticationErrortoo. The multipart path calledraise_for_status()bare, so a 401 or 403 on an upload surfaced a rawhttpx.HTTPStatusErrorwhile every other request raisedAuthenticationError. Pre-existing rather than introduced here, but squarely inside FR-015's "every failure the SDK observes as HTTP 401 or 403". The silent refresh already covered this path; only the error type was inconsistent.
Implementation:
infrahub_sdk/exceptions.pybecomes a package:base.py(the hand-written hierarchy),factory.py(two raise-time factories),__init__.py(a star-import façade). The import pathinfrahub_sdk.exceptionsis unchanged, and a committed snapshot test pins that nothing dropped out of it.- Fifteen call sites that each hand-rolled
" | ".join(messages)or built aGraphQLErrornow funnel through the factories, so envelope parsing lives in one place. - Both factories are total. Any shape the parser cannot read degrades to the generic exception that call site raised anyway, never to an SDK error of our own. That is the property the
malformed_*fixtures exist to pin.
What stayed the same: no message text changed, no class was removed from any MRO, and ApiError is inserted strictly between Error and the two classes, so every existing except and isinstance still matches exactly what it matched. The CLI error ladder is byte-for-byte untouched.
Suggested review order
infrahub_sdk/exceptions/base.pyandfactory.pyfor the new shape.infrahub_sdk/client.py_should_refresh_tokenfor the crash fix, and the two_execute_graphql_with_filemethods for the upload path.- The call sites in
object_store.py/file_handler.py, which are all the same edit. - Tests last.
How to review
Four things worth a sceptical eye:
- Exception types on unreadable 401/403 bodies changed. A non-JSON body previously raised
JsonDecodeError(or a rawjson.JSONDecodeErrorfrom the object store and file handler); a body with noerrorskey raisedTypeError. Both now raiseAuthenticationError. FR-015 requiresAuthenticationErrorfor every 401/403, so this fixes a pre-existing deviation, but it is visible to external consumers and has a changelog fragment. GraphQLError.errorsdrops entries that are not dicts and maps a non-listerrorsto[], so the declaredSequence[dict[str, Any]]is true at runtime. The payload still reaches the reader through the exception message. Consequence worth knowing: for a malformed envelopeinfrahubctlnow prints nothing and exits 1, where it previously printed the payload. Issue 2's T040 fixes the renderer.errorsis no longer declaredlist. It inheritsSequence[dict[str, Any]], which removes an unsound mutable-attribute override that pyright flags.is_unknown_field_errorandprint_graphql_errorswere widened to match. Runtime is unaffected; an external consumer only breaks if it annotateslistor calls.append()onexc.errors.- Six docstrings carry a
# noqa: DOC501. Ruff readsraise make_error(...)as raising something namedmake_errorand asks the docstring to document a function rather than an exception; the docstrings already name the real types. There is no config-level suppression, so the rule keeps working everywhere else. The directive sits after the docstring's closing quotes because that is the only placement ruff honours for this rule, andRUF100reports it as unused if ruff ever resolves a call to its return type.
The second commit annotates six tasks in tasks.md where the implementation diverged from the plan, each with the reasoning. The one that matters for the next issue: GraphQLError's optional message parameter is deferred to its first caller rather than added unused, so T035 adds it.
How to test
uv run pytest tests/unit/ -q
uv run invoke format lint-code
uv run invoke docs-generate docs-validate
Expected: unit suite green, ruff / ty / mypy clean across 160 files, docs in sync.
On macOS, 11 pre-existing failures are environmental and unrelated: 8 in tests/unit/pytest_plugin/ are psutil.cpu_freq() raising SystemError inside the testcontainers plugin, and 3 in tests/unit/ctl/ are Rich table assertions sensitive to terminal width.
Impact & rollout
- Backward compatibility: no
exceptclause in the SDK or CLI loses coverage. External consumers catchingJsonDecodeErrororTypeErroraround a 401/403 must catchAuthenticationErrorinstead; documented inchangelog/+error-catalogue-envelope.changed.md. - Performance: none. Parsing happens only on an error path that already decoded the body.
- Config/env changes: none.
- Deployment notes: safe to deploy on its own. Per the spec's landing order, the SDK merges before Infrahub bumps its submodule pointer, but that ordering constraint applies to issues 3 and 4, not this one.
Checklist
- Tests added/updated
- Changelog entry added (two fragments: one
changed, onefixed) - External docs updated (if user-facing or ops-facing change) — the catalogue topic page belongs to issue 3, once per-code bindings exist
- Internal .md docs updated (internal knowledge and AI code tools knowledge)