Ruby';s异常错误类
您可以创建异常的子类以使其更具描述性,但是应该如何设置默认的“message”Ruby';s异常错误类,ruby,Ruby,您可以创建异常的子类以使其更具描述性,但是应该如何设置默认的“message” class MyError < StandardError # default message = "You've triggered a MyError" end begin raise MyError, "A custom message" rescue Exception => e p e.message end begin raise MyError raise Excepti
class MyError < StandardError
# default message = "You've triggered a MyError"
end
begin
raise MyError, "A custom message"
rescue Exception => e
p e.message
end
begin
raise MyError
raise Exception => e
p e.message
end
class MyErrore
体育信息
结束
开始
升起我的箭
引发异常=>e
体育信息
结束
第一个应输出“自定义消息”
第二个应该输出“您触发了MyError”
关于最佳实践有什么建议吗?定义一个initialize方法,该方法将消息作为带有默认值的参数。然后用该消息调用
StandardError
的初始化方法(使用super
)
class MyError
您还可以覆盖子类中的消息
方法,并返回希望显示的字符串。我更喜欢这种方式,因为如果您想在显示消息之前做一些有趣的事情,它似乎可以让事情更干净一些
class CustomError < StandardError
def initialize(error_code, error_info)
@code, @info = error_code, error_info
end
def message
"<Code: #{@code}> <Info: #{@info}>"
end
end
class CustomError
只要super
就足够了。如果在没有参数列表的情况下调用super
,它只会传递所有参数,这就是为什么当您实际上不想传递任何参数时,必须显式调用super()
@JörgWMittag为什么所有自定义错误类都继承自StandardError
?有什么原因吗?@ArupRakshit,因为它是安全的。无论何时从错误中解救,它都应该是标准错误
(或更低),因为当点击CTL-C等时,更高级别的错误(如异常
)甚至会被抛出。有关更多信息,请参阅此@Sean,感谢链接。
class CustomError < StandardError
def initialize(error_code, error_info)
@code, @info = error_code, error_info
end
def message
"<Code: #{@code}> <Info: #{@info}>"
end
end