Handling errors¶
mreg-api raises attempts to raise its own exceptions for most error conditions, including HTTP errors, validation failures, and entity-lookup issues. This page explains the exception hierarchy, how to catch and inspect exceptions, and how to react to specific error conditions.
Exception hierarchy¶
All mreg-api exceptions inherit from a common MregApiBaseError base class.
The exception hierarchy is as follows:
MregApiBaseError
To catch all exceptions raised by mreg-api, one can use MregApiBaseError,
while ResponseError narrows to any error backed by an HTTP response,
and HTTPStatusError narrows further to 4xx/5xx responses.
Catching all exceptions¶
from mreg_api.exceptions import MregApiBaseError
try:
client.host.get("host.example.com")
except MregApiBaseError as exc:
# Anything the library raises lands here.
...
Catching HTTP status errors¶
HTTP operations against the server raise a subclass of HTTPStatusError based on the response status code, regardless of the HTTP method used:
ClientErrorfor 4xx responses, with dedicated subclasses for common status codes:BadRequestErrorfor 400 responses (e.g. invalid field values)UnauthorizedErrorfor 401 responses (e.g. a missing, invalid, or expired token)ForbiddenErrorfor 403 responsesNotFoundErrorfor 404 responsesConflictErrorfor 409 responses
ServerErrorfor 5xx responses
Other status codes raise the nearest parent class; use exc.status_code to inspect the exact code, and exc.request.method if you need the HTTP method.
Authentication errors subclass UnauthorizedError: login() raises LoginFailedError on rejected credentials, and test_auth() raises InvalidAuthTokenError on a rejected token.
For example:
from mreg_api import MregClient
from mreg_api.exceptions import ClientError, ConflictError, ServerError
client = MregClient(url="https://mreg.example.com")
try:
client.host.update("myhost.example.com", name="taken.example.com")
except ConflictError as exc:
# 409: the new name is already in use.
...
except ClientError as exc:
# Any other 4xx response.
...
except ServerError as exc:
# 5xx response.
...
Reading the error message¶
Raised ResponseError exceptions contain the HTTP response and parsed error details.
The detail attribute contains the main error message from the server without additional context,
while the formatted_message() method returns a more detailed message, optionally formatted as JSON.
try:
client.host.create(...)
except ResponseError as exc:
print(str(exc)) # or print(exc.formatted_message())
# 400 Bad Request: POST https://mreg.example.com/api/v1/hosts/
# 1 error:
# name: This field is required. (required)
print(exc.detail)
# This field is required.
print(exc.formatted_message(json=True))
# 400 Bad Request: POST https://mreg.example.com/api/v1/hosts/
# {
# "type": "validation_error",
# "errors": [ ... ]
# }
Note
str(ResponseError(...)) is equivalent to ResponseError(...).formatted_message() with no arguments.
Inspecting structured errors¶
Each ResponseError instance's .errors contains the parsed error response from the server as a MREGErrorResponse object.
If the response cannot be parsed, a default MREGErrorResponse with type "unknown" is returned.
Each MREGError object in the .errors list has a standardized code, the offending
field in attr, and a (generally) more verbose and human-readable detail.
try:
client.host.create(...)
except ResponseError as exc:
print(exc.errors.type) # e.g. "validation_error"
for err in exc.errors.errors:
print(err.code, err.attr, err.detail)
# required name This field is required.
Using the response object¶
ResponseError exceptions expose the underlying HTTP response object as .response, which can be used to inspect headers, status codes, and other details.
try:
client.host.update(host, name="newname")
except ResponseError as exc:
if exc.response.status_code == 404:
# some contrived example here :)
...
Client-side validation errors¶
When internal validation fails (e.g. a model is missing a required field), the library raises MregValidationError.
The exception wraps the underlying Pydantic validation error, which is available on .pydantic_error.
from mreg_api.exceptions import MregValidationError
try:
client.host.list()
except MregValidationError as exc:
print(exc) # includes the field, reason, and offending input
print(exc.pydantic_error) # the underlying pydantic.ValidationError, or None
Generally, this should not happen, and indicates a mismatch between what the server delivers, and what the client expects. If this problem persists, open an issue.
Other exceptions¶
These exception are less common, and typically indicate some user error or failsafe that is triggered, that must be handled carefully.
ForceMissing for destructive or unusual operations¶
PreconditionError (and more often, its subclass ForceMissing) is raised when an operation's precondition is not met. MREG allows destructive, potentially cascading, operations on resources with many-to-many relations, as well as other modifications that should be explicitly acknowledged by the user before proceeding.
from mreg_api.exceptions import PreconditionError # or ForceMissing
try:
client.zone.delete("somezone.example.com") # force missing
except PreconditionError as exc:
# Zone still has registered entries or subzones
# use some heuristic to determine if we should force deletion:
if len(client.zone.list_subzones("somezone.example.com")) <= 2:
client.zone.delete("somezone.example.com", force=True)
Currently, as of 0.6.0, these methods can raise ForceMissing if the precondition for the operation is not met:
MregClient.atom.deleteMregClient.role.deleteMregClient.ipaddress.associate_macMregClient.delegation.createMregClient.zone.verify_nameserversMregClient.zone.createMregClient.zone.set_nameserversMregClient.zone.delete
Reference¶
A complete API reference for all exceptions is available in the Exceptions reference section.