"""Error helpers for ows-royalties.""" import json from httpx import HTTPStatusError class OwsError(Exception): """Exception which contains HTTP response data for ows-royalties.""" def __init__(self, message: str, code: str = 'bad_request', status: int = 400): """Initialize exception.""" super().__init__() self.message = message self.code = code self.status = status def __str__(self): """Turn this exception into a string.""" return f'Status {self.status}: {self.message} ({self.code})' @classmethod def create_from_http_status_error(cls, http_status_error: HTTPStatusError): """Create OwsError from an HTTP status error.""" code = 'request_error' if hasattr(http_status_error, 'response') and hasattr( http_status_error.response, 'status_code' ): message = str(http_status_error) status = http_status_error.response.status_code if http_status_error.response.text: error_body = json.loads(http_status_error.response.text) code = error_body.get('code', code) message = error_body.get('message', message) return cls(message=message, code=code, status=status) return cls(message=str(http_status_error), code=code, status=400)