def _to_service_error()

in alibabacloud_oss_v2/_client.py [0:0]


def _to_service_error(response: HttpResponse) -> exceptions.ServiceError:
    timestamp = serde.deserialize_httptime(response.headers.get('Date'))
    content = response.content or b''
    response.close()

    error_fileds = {}
    code = 'BadErrorResponse'
    message = ''
    ec = ''
    request_id = ''
    err_body = b''
    try:
        err_body = content
        if len(err_body) == 0:
            err_body = base64.b64decode(
                response.headers.get('x-oss-err', ''))
        root = ET.fromstring(err_body)
        if root.tag == 'Error':
            for child in root:
                error_fileds[child.tag] = child.text
            message = error_fileds.get('Message', '')
            code = error_fileds.get('Code', '')
            ec = error_fileds.get('EC', '')
            request_id = error_fileds.get('RequestId', '')
        else:
            message = f'Expect root node Error, but get {root.tag}.'
    except ET.ParseError as e:
        errstr = err_body.decode()
        if '<Error>' in errstr and '</Error>' in errstr:
            m = re.search('<Code>(.*)</Code>', errstr)
            if m:
                code = m.group(1)
            m = re.search('<Message>(.*)</Message>', errstr)
            if m:
                message = m.group(1)
        if len(message) == 0:
            message = f'Failed to parse xml from response body due to: {str(e)}. With part response body {err_body[:256]}.'
    except Exception as e:
        message = f'The body of the response was not readable, due to : {str(e)}.'

    return exceptions.ServiceError(
        status_code=response.status_code,
        code=code,
        message=message,
        request_id=request_id or response.headers.get('x-oss-request-id', ''),
        ec=ec or response.headers.get('x-oss-ec', ''),
        timestamp=timestamp,
        request_target=f'{response.request.method} {response.request.url}',
        snapshot=content,
        headers=response.headers,
        error_fileds=error_fileds
    )