def listen(incoming_connection):
    logging.info('Listening for new b2b subs')
    while True:
        try:
            incoming_connection.drain_events()

        except KeyboardInterrupt:
            logging.info("Interrupted")
            break
        except Exception as exception:
            raise_error({"text": str(exception)})
            logging.error(str(exception))
def error_handler(err):
    logging.debug('-----------------')
    logging.error(str(err))
    logging.error(format_message('Unhandled exception: ' + str(err)))
    call_stack = traceback.format_exc()

    lines = call_stack.split("\n")
    for line in lines[0:-2]:
        logging.error(format_message(line))

    error = {
        "type": "F",
        "stack": lines[0:-2]
    }

    try:
        error["dict"] = json.loads(str(err))
    except ValueError as e:
        error["text"] = str(err)

    logging.error(json.dumps(error, indent=2))

    raise_error(error)
    return Response(json.dumps(error), status=500)
def complete_application(cursor, appn_id, data):
    # Submit registration
    url = app.config['LAND_CHARGES_URI'] + '/registrations'
    headers = get_headers({'Content-Type': 'application/json'})
    if 'lc_register_details' in data:
        response = requests.post(url, data=json.dumps(create_lc_registration(data)), headers=headers)
    else:  # banks registration
        response = requests.post(url, data=json.dumps(data['registration']), headers=headers)

    if response.status_code == 400:
        logging.error(response.text)
        raise ValidationError(response.text)

    elif response.status_code != 200:
        logging.error(response.text)
        error = json.loads(response.text)
        logging.error(json.dumps(error, indent=2))
        raise CaseworkAPIError(json.dumps(error))

    regns = response.json()

    # Insert print job
    errors = []
    try:
        insert_result_row(cursor, regns['request_id'], 'registration')
    except Exception as e:
        error = "Failed to insert print row. Message: {}".format(str(e))
        errors.append(error)
        logging.error(error)

    # Archive document
    document_id = data['application_data']['document_id']
    if data['form'] == 'K6':
        reg_type = 'priority_notices'
    else:
        reg_type = 'new_registrations'

    try:
        for regn in regns[reg_type]:
            number = regn['number']
            date = regn['date']
            store_image_for_later(cursor, document_id, number, date)
    except Exception as e:
        error = "Failed to insert image for later. Message: {}".format(str(e))
        errors.append(error)
        logging.error(error)

    # Delete work-item
    try:
        delete_application(cursor, appn_id)
    except Exception as e:
        error = "Failed to delete application row. Message: {}".format(str(e))
        errors.append(error)
        logging.error(error)

    # return regn nos

    for error in errors:
        raise_error(error)

    return regns