Files
seismo-relay/sfm/device_access/errors.py
T

74 lines
1.8 KiB
Python

"""Typed device errors, each with the HTTP status the endpoints return."""
from __future__ import annotations
import micromate.protocol as _mm_proto
import minimateplus.protocol as _mmp_proto
class DeviceError(Exception):
http_status = 500
class BadRequest(DeviceError):
http_status = 422
class NotSupported(DeviceError):
http_status = 501
class WrongUnit(DeviceError):
http_status = 409
class UnitBusy(DeviceError):
http_status = 423
class ConnectFailed(DeviceError):
http_status = 503
class CallHomeInProgress(DeviceError):
http_status = 503
class NoAnswer(DeviceError):
http_status = 504
class MalformedReply(DeviceError):
http_status = 502
class EventNotFound(DeviceError):
http_status = 404
class StaleEvent(DeviceError):
"""The event at that key is not the one listed -- the unit was erased, or
its memory wrapped, since the list was read."""
http_status = 409
_TIMEOUTS = (_mm_proto.TimeoutError, _mmp_proto.TimeoutError)
_PROTOCOL = (_mm_proto.ProtocolError, _mmp_proto.ProtocolError)
def translate(exc: BaseException, *, connecting: bool) -> DeviceError:
"""Map a library exception to a typed error.
Order matters: each library's TimeoutError is a ProtocolError subclass, and
the builtin TimeoutError (a failed TCP connect) is an OSError.
"""
if isinstance(exc, DeviceError):
return exc
if isinstance(exc, _TIMEOUTS):
return NoAnswer(f"the unit did not answer: {exc}")
if isinstance(exc, _PROTOCOL):
return MalformedReply(f"bad reply from the unit: {exc}")
if isinstance(exc, OSError):
what = "could not connect" if connecting else "connection lost"
return ConnectFailed(f"{what}: {exc}")
return DeviceError(f"device error: {exc}")