如何使用自定义错误消息
How to use custom error messages
当我使用非数字输入测试我的代码时,Ruby 会引发一条默认消息。相反,无论何时引发异常,我都希望使用默认 backtrace.inspect
打印我的自定义消息。我预计:
"oops... That was not a number"
将被提出而不是:
invalid value for Float(): "h\n" (ArgumentError)
我写了下面的代码,灵感来自于以下文档:
Whosebug,
rubylearning,
github.
class MyCustomError < StandardError
def message
"oops... That was not a number"
end
end
def print_a_number
begin
puts "chose a number"
number = Float(gets)
raise MyCustomError unless number.is_a? Numeric
puts "The number you chose is #{number}"
rescue MyCustomError => err
puts err.message
puts err.backtrace.inspect
end
end
下面的代码确实按照我的预期运行;我不明白为什么下面的代码会打印我的默认消息,而上面的代码却不会:
class MyCustomError < StandardError
def message
"The file you want to open does not exist"
end
end
def open_a_file
begin
puts "What file do you want to open?"
file2open = gets.chomp
raise MyCustomError unless File.file?(file2open)
File.open(file2open, 'r') { |x|
while line = x.gets
puts line
end
}
rescue MyCustomError => err
puts err.message
puts err.backtrace.inspect
end
end
您的 unless
条件永远不会为假:Kernel#Float
将引发异常(在这种情况下您的条件甚至没有达到)或 return a Float
(它是 Numeric
的子类)。
只需像这样修改您的脚本。
class MyCustomError < StandardError
def message
"oops... That was not a number"
end
end
def print_a_number
begin
puts "chose a number"
number = Float(gets) rescue false
raise MyCustomError unless number.is_a? Numeric
puts "The number you chose is #{number}"
rescue MyCustomError => err
puts err.message
puts err.backtrace.inspect
end
end
当我使用非数字输入测试我的代码时,Ruby 会引发一条默认消息。相反,无论何时引发异常,我都希望使用默认 backtrace.inspect
打印我的自定义消息。我预计:
"oops... That was not a number"
将被提出而不是:
invalid value for Float(): "h\n" (ArgumentError)
我写了下面的代码,灵感来自于以下文档: Whosebug, rubylearning, github.
class MyCustomError < StandardError
def message
"oops... That was not a number"
end
end
def print_a_number
begin
puts "chose a number"
number = Float(gets)
raise MyCustomError unless number.is_a? Numeric
puts "The number you chose is #{number}"
rescue MyCustomError => err
puts err.message
puts err.backtrace.inspect
end
end
下面的代码确实按照我的预期运行;我不明白为什么下面的代码会打印我的默认消息,而上面的代码却不会:
class MyCustomError < StandardError
def message
"The file you want to open does not exist"
end
end
def open_a_file
begin
puts "What file do you want to open?"
file2open = gets.chomp
raise MyCustomError unless File.file?(file2open)
File.open(file2open, 'r') { |x|
while line = x.gets
puts line
end
}
rescue MyCustomError => err
puts err.message
puts err.backtrace.inspect
end
end
您的 unless
条件永远不会为假:Kernel#Float
将引发异常(在这种情况下您的条件甚至没有达到)或 return a Float
(它是 Numeric
的子类)。
只需像这样修改您的脚本。
class MyCustomError < StandardError
def message
"oops... That was not a number"
end
end
def print_a_number
begin
puts "chose a number"
number = Float(gets) rescue false
raise MyCustomError unless number.is_a? Numeric
puts "The number you chose is #{number}"
rescue MyCustomError => err
puts err.message
puts err.backtrace.inspect
end
end