Skip to content

Responses and errors

An awaited send returns a ClientResponse when Orionis receives a complete, bounded response, including for HTTP 404 or 503. If the connection fails before completion, the await raises an exception. Once you have the response, its accessors are synchronous. The status, headers and bytes remain available after the connection is released.

Return a product or handle an expected 404

Section titled “Return a product or handle an expected 404”

Use the catalog profile. Suppose its product endpoint returns {"data": {"id": 42, "name": "Notebook"}} and uses 404 for a missing product. Handle that outcome explicitly, then let the other error statuses reach the caller.

from orionis.http.client import IHttpManager
async def product_or_none(http: IHttpManager, product_id: int) -> dict | None:
result = await http.client("catalog").get(f"/products/{product_id}")
if result.status() == 404:
return None
return result.throw().json("data")

Calling this function with ID 42 yields the product dictionary for that example; a 404 yields None. A 500 raises HttpStatusException even when the upstream error body is HTML. If you catch that exception, error.response contains the original response, so you can inspect its status or a header such as Retry-After.

What you needAccessor and result
Exact statusstatus() returns the integer. ok() is true only for 200.
Any successful HTTP statussuccessful() covers 200–299, including 201 Created and 204 No Content.
Client or server errorclientError() covers 400–499, serverError() 500–599, and failed() either range.
Raise on HTTP errorsthrow() raises for 4xx and 5xx. For other statuses it returns the same response for chaining.
Redirect3xx is returned directly. Check status() and header("Location"); follow up only if your application expects that destination.
  • body() returns the complete bytes. A HEAD request and a 1xx, 204 or 304 response have an empty body. Check for these outcomes before attempting JSON decoding.
  • text() decodes according to the charset in Content-Type, defaulting to UTF-8. Unknown charsets or invalid bytes raise HttpDecodeException.
  • json() parses the body bytes, regardless of the media type. Empty or malformed JSON and nonstandard numeric constants such as NaN raise HttpDecodeException. Parsing happens on each call; keep the decoded document when extracting many fields.
  • json("data.name") walks dictionary keys. Retrieve a list first, then index it in Python. A missing key, or a traversal through a value that is not a dictionary, raises KeyError. default= supplies a fallback for a missing path. A present JSON null returns None and malformed JSON still raises.

headers() returns the ordered tuple of all name/value pairs. header(name, default=None) returns the first matching value, and headerValues(name) returns every matching value in order, or an empty tuple. Both lookups ignore letter case. Use headerValues("Set-Cookie") for repeated cookies; converting the pairs to a dictionary would lose duplicates. Received cookies are not stored for later requests.

This example supplies a response locally so you can inspect the result after leaving the fake scope. Run it in a booted application with the catalog profile.

from orionis.support.facades import Http
async def inspect_product() -> None:
url = "https://catalog.example.com/products/42"
payload = {"data": {"name": "Notebook", "tags": ["paper"], "owner": None}}
fixture = Http.response(payload, headers=[("X-Tag", "new"), ("X-Tag", "sale")])
async with Http.fake({("GET", url): fixture}):
result = await Http.client("catalog").get("/products/42")
assert result.ok() and result.successful()
assert result.json("data.tags")[0] == "paper"
assert result.json("data.owner", default="guest") is None
assert result.json("data.currency", default="USD") == "USD"
assert result.header("x-tag") == "new"
assert result.headerValues("X-Tag") == ("new", "sale")

Import the following exceptions from orionis.http.client.exceptions. They all derive from HttpClientException. Catch the most specific type you can handle.

ExceptionWhen it happensWhat to inspect or do
HttpConfigurationExceptionInvalid outbound configuration or unknown named client.Check the profile spelling, its allowed origin and its ceilings.
HttpRequestExceptionInvalid request arguments, headers, credentials, body combination or time budget.Correct the builder or send options before trying again.
HttpDestinationExceptionInvalid HTTPS destination or attempted use of a different, unapproved origin. Subclass of HttpRequestException.Check the configured origin and whether the endpoint is a relative path.
HttpStatusExceptionYou called throw() on 4xx/5xx.Read error.response.status() and handle statuses meaningful to the integration.
HttpTimeoutExceptionA time budget expired. Subclass of HttpTransportException.Read error.phase to distinguish connect, read, write, pool or deadline. Catch this before the broader transport type.
HttpTransportExceptionConnection, TLS, read, write or HTTP protocol failure.error.category identifies connect, read, write or protocol; a timeout has category timeout. A write failure can leave the remote outcome unknown.
HttpSizeLimitExceptionA request or response exceeded its size budget.Check error.direction (request or response). Reduce the payload, select fewer fields or paginate upstream.
HttpDecodeExceptionUnsupported response content encoding, undecodable text, or invalid JSON.A compressed response can fail during the await. For a text or JSON failure, inspect the status and media type before choosing a decoder.
HttpCapacityExceptionLocal waiting slots or preparation workers are full.Bound the number of submissions. Concurrency and lifecycle
HttpClosedExceptionWork used a closed runtime owner or inherited a fake scope that already ended.Await child tasks within their owning lifecycle or test scope.
HttpFakeExceptionInvalid fixture status/body, missing fixture or exhausted sequence.Compare the verb and final absolute URL, including the query string. Test outbound requests

KeyError from a missing JSON path and asyncio.CancelledError from caller cancellation sit outside this hierarchy. Let cancellation reach the caller after any cleanup. Orionis makes one attempt per send. In particular, check the upstream outcome before your application considers repeating a write.