【问题标题】:Handling errors with Genie使用 Genie 处理错误
【发布时间】:2016-07-17 00:31:49
【问题描述】:

我正在尝试将 python class 重构为 Genie,但我不知道如何处理错误。一些指针将不胜感激。

如果我理解正确的话,使用 Genie 处理错误的方式是使用 Try...except 块,但是如何将以下类型的错误处理转换为这种范例:

# Enable dictionary/list-style access to options and arguments.
def __getitem__(self, key):
    if isinstance(key, int):
        if key < len(self.arguments):
            return self.arguments[key]
        else:
            raise ArgParserError(
                "positional argument index [%s] is out of bounds" % key
            )
    else:
        option = self._get_opt(key)
        return option.value

我现在的代码看起来像(在 Genie 中):

def getitem (key:int):string
    if key.is_int()
        if key < len(_arguments)
            return _arguments[key]
        else
            raise ArgParserError(
                "positional argument index [%s] is out of bounds", key
            )
    else
        var option = _get_opt(key)
        return option.value

这是一个虚拟代码,我只是对问题进行建模,我知道它不会按原样编译。我只是在寻找一个关于如何从 python 中转换 '''raise''' 命令的指针。

【问题讨论】:

    标签: genie


    【解决方案1】:

    你需要将错误类型定义为exception,然后标识你的getitem函数raises这样的错误:

    exception ArgParserError
        OUT_OF_BOUNDS
    
    def getitem( key:int ):string raises ArgParserError
        if key < len(_arguments)
            return _arguments[key]
        else
            raise new ArgParserError.OUT_OF_BOUNDS(
                "positional argument index [%s] is out of bounds", key
                 )
    

    Genie 是静态类型的,所以if key.is_int() 是不必要的。 Vala 编译器将在编译时检查所有对 getitem 函数的调用是否将整数作为参数传递。

    另一种方法是使用out 参数作为结果值,并使用函数的返回值来指示结果是否有效:

    def getitem( key:uint, out value:string ):bool
        result:bool = false
        value = ""
        if key < _arguments.length
            value = _arguments[ key ]
            result = true
        else
            info( "positional argument index [%s] is out of bounds", key )
        return result
    

    通过将键设为无符号整数uint,不能传递负索引。对info() 的调用将记录超出范围索引的一些详细信息,以便您稍后需要它进行调试。

    【讨论】:

    • OUT_OF_BOUNDS 是我可以想出的类型定义,还是我可以使用的选项列表?
    • 示例使用我自己编的,你可以随意改。如果您想使用这些异常库定义,例如 GLib.IOError
    猜你喜欢
    • 2021-11-20
    • 2011-01-24
    • 2015-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多