Ruby中如何识别并处理显示错误的具体模式?
- 内容介绍
- 文章标签
- 相关推荐
本文共计243个文字,预计阅读时间需要1分钟。
在我的代码中,我通常使用以下设置:pythonmodule MyLib VERSION=2.1.1 ERROR=[ You can either give one arg and a block or two args, not both., Yadda yadda... ]end
def my_method(*args)
在我的代码中,我通常使用以下设置: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
本文共计243个文字,预计阅读时间需要1分钟。
在我的代码中,我通常使用以下设置:pythonmodule MyLib VERSION=2.1.1 ERROR=[ You can either give one arg and a block or two args, not both., Yadda yadda... ]end
def my_method(*args)
在我的代码中,我通常使用以下设置: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

