Builds an L{ErrorMessage<pyamf.flex.messaging.ErrorMessage>} based on the
    last traceback and the request that was sent.

def generate_error(request, cls, e, tb, include_traceback=False):
    """
    Builds an L{ErrorMessage<pyamf.flex.messaging.ErrorMessage>} based on the
    last traceback and the request that was sent.
    """
    import traceback

    if hasattr(cls, '_amf_code'):
        code = cls._amf_code
    else:
        code = cls.__name__

    details = None
    rootCause = None

    if include_traceback:
        details = traceback.format_exception(cls, e, tb)
        rootCause = e

    faultDetail = None
    faultString = None

    if hasattr(e, 'message'):
        faultString = unicode(e.message)
    elif hasattr(e, 'args') and e.args:
        if isinstance(e.args[0], pyamf.python.str_types):
            faultString = unicode(e.args[0])

    if details:
        faultDetail = unicode(details)

    return messaging.ErrorMessage(
        messageId=generate_random_id(),
        clientId=generate_random_id(),
        timestamp=calendar.timegm(time.gmtime()),
        correlationId=request.messageId,
        faultCode=code,
        faultString=faultString,
        faultDetail=faultDetail,
        extendedData=details,
        rootCause=rootCause)