Handle the Errors

When the server responds with an unexpected status code, the client raises an exception of aas_client3_2.errors. All the exceptions of the client derive from Error:

The errors of the network, such as a refused connection or a timeout, are raised by the transport, and propagate unchanged through the client.

Catch an Error

import requests

import aas_core3_2.types as aas_types

from aas_client3_2 import (
    errors as aas_client_errors,
    http as aas_client_http,
    requests_transport as aas_client_requests_transport,
    submodel_repository as aas_client_submodel_repository,
)

server = aas_client_http.Server(
    transport=aas_client_requests_transport.RequestsTransport(
        requests.Session()
    ),
    base_url="http://localhost:5005",
)

try:
    aas_client_submodel_repository.get_submodel_by_id(
        server,
        "https://example.com/ids/sm/getting-started/does-not-exist",
    )
except aas_client_errors.NotFound as error:
    print(f"Not found: {error.response.status_code}")
# Prints: Not found: 404

The Messages of the Server

The server explains an error in a Result with messages. The client parses it, if the server gives one, into result. The raw response is always available as response:

submodel = aas_types.Submodel(
    id="https://example.com/ids/sm/getting-started/errors"
)
aas_client_submodel_repository.post_submodel(server, submodel)

try:
    # The submodel exists already.
    aas_client_submodel_repository.post_submodel(server, submodel)
except aas_client_errors.HttpError as error:
    print(type(error).__name__)
    if error.result is not None:
        for message in error.result.over_messages_or_empty():
            print(message.message_type.value, message.text)

The message of the exception itself also contains the status code and the messages, so it is informative in the logs.

Operations the Server Does Not Implement

A server needs not implement all the operations; it announces what it implements by its profiles (see description). If you call an operation it does not implement, the specification lets the server respond either with 501, and the client raises NotImplementedByServer, or with 403, and the client raises Forbidden, the same as for a missing permission.

Clean Up

Delete what we created in this chapter, so that you can run the code of this chapter again. The identifiers are unique, so the server would refuse to create the submodel a second time. This is exactly the error which we provoked above:

aas_client_submodel_repository.delete_submodel_by_id(
    server, submodel.id
)