# SPDX-FileCopyrightText: 2026 aas-client3.2-python AUTHORS
#
# SPDX-License-Identifier: MIT
"""
Map the unexpected responses of the server to exceptions.
A response with an unexpected status code raises an :py:class:`HttpError`, or one
of its subclasses. A response which can not be de-serialized raises an
:py:class:`UnexpectedResponse`.
We wrap the HTTP errors in our own exceptions instead of letting the transport
raise them, or returning the status codes to the users, for the following reasons:
* **The specification gives the status codes a meaning.**
Section "Mapping of Status Codes" of the specification (Table 4, see
https://industrialdigitaltwin.io/aas-specifications/IDTA-01002/v3.2/http-rest-api/http-rest-api.html#mapping-of-status-codes)
maps the generic outcomes of the operations to the HTTP status codes, such as
404 for a missing resource and 409 for a resource which already exists.
Hence, the users catch :py:class:`NotFound` or :py:class:`Conflict` instead of
comparing integers, and the functions return only native data in the happy path.
* **We follow the meanings of Table 4 literally.**
A status code which a server easily sends in a different situation keeps its own
exception, so that the users do not draw the wrong conclusion:
* 403 means that "the server refuses the action due to certain restrictions,
e.g. profiles or roles". Hence, a server which implements only a subset of the
operations as a service specification profile might respond with
:py:class:`Forbidden`, the same as for a missing role.
* 405 means that "the server rejected the request for the requested resource,
e.g. /invoke only for the operation submodel element". This is a request which
does not fit the resource, not a missing implementation, so we raise
:py:class:`MethodNotAllowed`.
* 501 means that "the server does not support the functionality to fulfill the
request", so we raise :py:class:`NotImplementedByServer`.
* **The specification defines the payload of the error responses.**
The servers report their messages as a ``Result`` with a list of ``Message``
(see
https://industrialdigitaltwin.io/aas-specifications/IDTA-01002/v3.2/specification/interfaces-payload.html#Result).
We parse it into :py:attr:`HttpError.result`, so that the users get the messages
of the server as native data, and the message of the exception includes them.
However, the specification does not oblige the servers to always provide the
messages, and a reverse proxy in front of a server responds with a body of its
own. Hence, the result is optional, and the exception always carries the raw
:py:attr:`HttpError.response`, including the headers such as
``WWW-Authenticate``.
* **The client does not depend on any HTTP library.**
The transports report every status code as an ordinary response, so the errors
of the client do not depend on the exceptions of an HTTP library, such as
:py:class:`requests.HTTPError`. Only the network errors are raised by the
transport itself, and propagate unchanged. All the errors of the client derive
from :py:class:`Error`, so that the users can tell them apart from the network
errors.
"""
import json
from typing import AbstractSet, Dict, Final, List, Optional, Type
import aas_core3_2.jsonization as aas_jsonization
import aas_core3_2.types as aas_types
from aas_client3_2 import http
#: Maximum number of bytes read from the body of an error response when streaming,
#: so that a misbehaving server can not exhaust the memory
MAX_STREAMED_ERROR_BODY_SIZE: Final[int] = 1024 * 1024
[docs]
class Error(Exception):
"""Represent the base for all the errors raised by the client."""
[docs]
class HttpError(Error):
"""Signal that the server responded with an unexpected status code."""
#: Raw response of the server
response: http.Response
#: Messages of the server, if the body could be parsed as a result
result: Optional[aas_types.Result]
[docs]
def __init__(
self, response: http.Response, result: Optional[aas_types.Result]
) -> None:
"""Initialize with the given values."""
self.response = response
self.result = result
super().__init__(_describe(response, result))
[docs]
class BadRequest(HttpError):
"""Signal that the server responded with 400 Bad Request."""
[docs]
class Unauthorized(HttpError):
"""
Signal that the server responded with 401 Unauthorized.
The header ``WWW-Authenticate`` of the :py:attr:`~HttpError.response` usually
tells why, for example, ``error="invalid_token"``.
"""
[docs]
class Forbidden(HttpError):
"""Signal that the server responded with 403 Forbidden."""
[docs]
class NotFound(HttpError):
"""Signal that the server responded with 404 Not Found."""
[docs]
class Conflict(HttpError):
"""Signal that the server responded with 409 Conflict."""
[docs]
class MethodNotAllowed(HttpError):
"""
Signal that the server responded with 405 Method Not Allowed.
According to the specification, the request does not fit the requested
resource, for example, ``/invoke`` on a submodel element which is not
an operation.
"""
[docs]
class NotImplementedByServer(HttpError):
"""
Signal that the server does not implement the operation.
The server responded with 501 Not Implemented.
"""
[docs]
class UnexpectedResponse(Error):
"""Signal that the response of the server could not be de-serialized."""
#: Raw response of the server
response: http.Response
#: Error raised while de-serializing the response
error: Exception
[docs]
def __init__(self, response: http.Response, error: Exception) -> None:
"""Initialize with the given values."""
self.response = response
self.error = error
super().__init__(
f"Failed to de-serialize the response with "
f"the status code {response.status_code}: {_describe_error(error)}"
)
_ERROR_TYPE_BY_STATUS_CODE: Final[Dict[int, Type[HttpError]]] = {
400: BadRequest,
401: Unauthorized,
403: Forbidden,
404: NotFound,
405: MethodNotAllowed,
409: Conflict,
501: NotImplementedByServer,
}
def _describe_error(error: Exception) -> str:
"""Describe the de-serialization error including its path, if available."""
if isinstance(error, aas_jsonization.DeserializationException):
return f"{error.path}: {error.cause}"
return str(error)
def _describe(response: http.Response, result: Optional[aas_types.Result]) -> str:
"""Describe the unexpected status code together with the server's messages."""
parts: List[str] = [f"Unexpected status code {response.status_code}"]
if result is not None:
for message in result.over_messages_or_empty():
code = f" ({message.code})" if message.code is not None else ""
parts.append(f"{message.message_type.value}{code}: {message.text}")
return "; ".join(parts)
[docs]
def parse_result(response: http.Response) -> Optional[aas_types.Result]:
"""
Parse the body of an error response as a result with the server's messages.
The body is parsed only if its ``Content-Type`` is JSON. The servers often send
HTML or plain text as an error body, for example, from a reverse proxy; the
error is still raised then, only without the messages.
:param response: error response
:returns: the result, or None if the body is not a valid result in JSON
"""
if len(response.body) == 0 or not http.has_media_type(
response.headers, "application/json"
):
return None
try:
jsonable = json.loads(response.body)
return aas_jsonization.result_from_jsonable(jsonable)
except (ValueError, aas_jsonization.DeserializationException):
return None
[docs]
def error_from_response(response: http.Response) -> HttpError:
"""
Map the :paramref:`response` with an unexpected status code to an error.
:param response: response of the server
:returns: the error to be raised
"""
error_type = _ERROR_TYPE_BY_STATUS_CODE.get(response.status_code, HttpError)
return error_type(response, parse_result(response))
[docs]
def raise_for_unexpected_status(
response: http.Response, expected: AbstractSet[int]
) -> None:
"""
Raise the error mapped from :paramref:`response` if its status is unexpected.
:param response: response of the server
:param expected: status codes which signal success
:raises: :py:class:`HttpError` if the status code is not in :paramref:`expected`
"""
if response.status_code not in expected:
raise error_from_response(response)
[docs]
def error_from_streamed_response(
streamed: http.StreamedResponse,
max_body_size: int = MAX_STREAMED_ERROR_BODY_SIZE,
) -> HttpError:
"""
Read at most :paramref:`max_body_size` bytes of the body, and map it to an error.
The rest of the body is not read. The caller releases the connection by
exiting the context of the stream.
:param streamed: streamed response with an unexpected status code
:param max_body_size: maximum number of bytes read from the body
:returns: the error to be raised
"""
chunks: List[bytes] = []
size = 0
for chunk in streamed.chunks:
remaining = max_body_size - size
if len(chunk) >= remaining:
chunks.append(chunk[:remaining])
break
chunks.append(chunk)
size += len(chunk)
return error_from_response(
http.Response(
status_code=streamed.status_code,
headers=streamed.headers,
body=b"".join(chunks),
)
)