2011-05-05 91 views
3

在我的代码,我通常采用以下设置:Patters显示错误

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 

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

回答

7

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

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