<commit_before>"""
Common message types and marshalling helper functions
"""
import base64
import copy
import json
import time

from anchore_engine.subsys import logger


def make_response_error(errmsg, in_httpcode=None, details=None):
    if details is None:
        details = {}
    if not in_httpcode:
        httpcode = 500
    else:
        httpcode = in_httpcode

    msg = str(errmsg)

    ret = {
        'message': msg,
        'httpcode': int(httpcode),
        'detail': details
    }
    if 'error_codes' not in ret['detail']:
        ret['detail']['error_codes'] = []

    if isinstance(errmsg, Exception):
        if 'anchore_error_json' in errmsg.__dict__:
            # Try to load it as json
            try:
                err_json = json.loads(errmsg.__dict__.get('anchore_error_json', None))
            except ValueError:
                # Then it may just be a string, we cannot do anything with it
                logger.debug('Failed to parse anchore_error_json as json')
                return ret

            if {'message', 'httpcode', 'detail'}.issubset(set(err_json)):
                ret.update(err_json)

            try:
                if {'error_code'}.issubset(set(err_json)) and err_json.get('error_code', None):
                    if 'error_codes' not in ret['detail']:
                        ret['detail']['error_codes'] = []
                    ret['detail']['error_codes'].append(err_json.get('error_code'))
            except KeyError:
                logger.warn("unable to marshal error details: source error {}".format(errmsg.__dict__))
    return ret


def make_anchore_exception(err, input_message=None, input_httpcode=None, input_detail=None, override_existing=False, input_error_codes=None):
    ret = Exception(err)

    if not input_message:
        message = str(err)
    else:
        message = input_message

    if input_detail != None:
        detail = input_detail
    else:
        detail = {'raw_exception_message': str(err)}

    if input_error_codes != None:
        error_codes = input_error_codes
    else:
        error_codes = []

    if not input_httpcode:
        httpcode = 500
    else:
        httpcode = input_httpcode

    anchore_error_json = {}
    try:
        if isinstance(err, Exception):
            if 'anchore_error_json' in err.__dict__:
                anchore_error_json.update(err.__dict__['anchore_error_json'])

            if 'error_code' in err.__dict__:
                error_codes.append(err.__dict__.get('error_code'))
    except:<commit_msg>improve handling based on type of error_json, catch typeerror as well use getattr/hasattr<commit_after>"""
Common message types and marshalling helper functions
"""
import base64
import copy
import json
import time

from anchore_engine.subsys import logger


def make_response_error(errmsg, in_httpcode=None, details=None):
    if details is None:
        details = {}
    if not in_httpcode:
        httpcode = 500
    else:
        httpcode = in_httpcode

    msg = str(errmsg)

    ret = {
        'message': msg,
        'httpcode': int(httpcode),
        'detail': details
    }
    if 'error_codes' not in ret['detail']:
        ret['detail']['error_codes'] = []

    if isinstance(errmsg, Exception):
        if not hasattr(errmsg, 'anchore_error_json'):
            return ret

        # Try to load it as json
        try:
            anchore_error_json = getattr(errmsg, 'anchore_error_json', None)
            if isinstance(anchore_error_json, dict):
                err_json = anchore_error_json
            else:
                err_json = json.loads(anchore_error_json)
        except (TypeError, ValueError):
            # Then it may just be a string, we cannot do anything with it
            logger.debug('Failed to parse anchore_error_json as json')
            return ret

        if {'message', 'httpcode', 'detail'}.issubset(set(err_json)):
            ret.update(err_json)

        try:
            if {'error_code'}.issubset(set(err_json)) and err_json.get('error_code', None):
                if 'error_codes' not in ret['detail']:
                    ret['detail']['error_codes'] = []
                ret['detail']['error_codes'].append(err_json.get('error_code'))
        except KeyError:
            logger.warn("unable to marshal error details: source error {}".format(errmsg.__dict__))
    return ret


def make_anchore_exception(err, input_message=None, input_httpcode=None, input_detail=None, override_existing=False, input_error_codes=None):
    ret = Exception(err)

    if not input_message:
        message = str(err)
    else:
        message = input_message

    if input_detail != None:
        detail = input_detail
    else:
        detail = {'raw_exception_message': str(err)}

    if input_error_codes != None:
        error_codes = input_error_codes
    else:
        error_codes = []

    if not input_httpcode:
        httpcode = 500
    else:
        httpcode = input_httpcode

    anchore_error_json = {}
    try:
        if isinstance(err, Exception):
            if hasattr(err, 'anchore_error_json'):
                anchore_error_json.update(getattr(err, 'anchore_error_json'))

            if hasattr(err, 'error_code'):
                error_codes.append(getattr(err, 'error_code'))
    except:
{'fraction_non_alphanumeric': 0.09954579863739592, 'fraction_numerical': 0.003028009084027252, 'mean_word_length': 2.376996805111821, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3606017', 'n_tokens_mistral': 1572, 'n_tokens_neox': 1513, 'n_words': 383}