gpt4 book ai didi

ruby - 显示错误的模式

转载 作者:数据小太阳 更新时间:2023-10-29 07:48:52 25 4
gpt4 key购买 nike

在我的代码中,我通常采用以下设置:

module MyLib
VERSION = "0.1.1"
ERROR = [
"You can either give one arg and a block or two args, not both.",
"Yadda yadda..."
]
end

然后在我的代码中的某处:

def my_method(*args, &blk)
raise(ArgumentError, MyLib::ERROR[0]) if (...condition snipped...)
end

是否有更好的方法来定义错误消息?

最佳答案

您可以定义自己的异常类:

module MyLib
class FooError < ArgumentError
def to_s
"You can either give one arg and a block or two args, not both.",
end
end
end

现在如果你提高它:

raise MyLib::FooError
MyLib::FooError: You can either give one arg and a block or two args, not both.
from (irb):46

如果你想处理它:

rescue MyLib::FooError

关于ruby - 显示错误的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5893537/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com