返回hyperledger锯齿形事务处理器上的自定义错误

2024-06-10 07:53:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用python sdk开发一个自定义事务处理器por hyperledger sawtooth

是否可以向请求事务的客户端返回自定义错误?客户如何知道交易未被处理的原因

当事务由于任何验证错误而无法完成时,我需要从apply()方法中返回一个错误,以便发出请求的客户端可以获得有关错误的一些反馈,以便向用户显示该错误

def apply(self, transaction, context):

在我检查过的示例中,代码会引发异常,但这会结束处理器的执行

知道我该怎么做吗


Tags: 方法用户客户端客户错误sdk原因交易
3条回答

您可以定义自己的自定义错误,让客户确切地知道发生了什么错误:

class ValidationError(Exception):
    """Exception raised for validation errors.

    Attributes:
        reason   reason of the error
        message   explanation of the error
    """

    def __init__(self, reason, message="Validation failed"):
        self.reason = reason
        self.message = message
        super().__init__(self.message)

    def __str__(self):
        # the return value of this function will be the error message
        return f'{self.reason} -> {self.message}'

然后您可以将该错误集成到代码中,例如:

def apply(self, transaction, context):
    try:
        if network_connection is False:
            raise ValidationError("Missing Network Connection")

        # your code here

        if success is False:
            raise ValidationError("Unknown reason")

    except Exception as e:
        print(e)

例如,如果在执行apply()函数之前将network_connection设置为False,则使用e打印的消息将是:

ValidationError: Missing Network Connection -> Validation failed

然后可以将此消息发送到客户端

这不能通过使用验证程序映像来完成。 您必须分叉https://github.com/hyperledger/sawtooth-corerepo并实现您自己的逻辑,以便在任何自定义情况下使验证器回复客户机

如果您希望这样做以避免InvalidTransaction异常的无限循环,那么可以从my forkhttps://github.com/charalarg/sawtooth-core构建并使用验证器,而不是使用锯齿验证器docker映像。它是sawtooth(1.2.6)的最新版本,修复了无限循环错误

我也有同样的问题,我也试图找到一种方法来避免事务执行,因为这个错误,但我最终应用了这个修复。 https://github.com/Remmeauth/sawtooth-core/pull/5

您可以尝试以下方法:

def apply(self, transaction, context):
    try:
        pass
        # your code
    except Exception as e:
        print(e)

其中,不使用print()调用,而是将e字符串发送到客户端,因为它将包含错误原因

相关问题 更多 >