在Ruby中使用特定的代码库时,我经常发现自己不知道要解救什么异常.
例如,我经常使用HTTParty来处理我的rails/sinatra app会发出的任何HTTP请求.我挖掘了HTTParty的代码,发现了一个包含已定义的异常的文件.大!我会在提出请求时拯救他们.
为了测试它,我为请求输入了一个虚假的域名,但我没有预期的HTTParty :: ResponseError异常,而是得到了一个SocketError异常.
处理这个问题的最佳方法是什么?我知道HTTParty是Ruby实现的包装器,这可能是抛出SocketError异常的原因.但我怎么知道呢?
我可以通过拯救"异常"来解决这个问题,但这是非常糟糕的做法.我宁愿清楚我可能造成的异常并处理这些异常.
编辑:我应该澄清,真正促使我创建这个问题的是我不知道如何能够找出在调用特定函数时可能引发的异常...也就是说,无需查看每个函数调用在堆栈中.
我需要在提交表单后进行一些处理,最终将多个记录保存在多个表中。因为我需要它要么全有要么全无,所以我将它包装在一个事务块中。该块似乎工作得很好,但是我不知道如何检查事务是否成功,以便我可以返回适当的响应。
...
# Start a transaction block so we can back out if anything fails
ActiveRecord::Base.transaction do
# Journal Entry for from_account
gle = from_account.gl_journal_entries.create(....)
# Journal Line (x2)
gle.gl_journal_lines.create(....)
gle.gl_journal_lines.create(....)
# Journal Entry for to_account
gle = to_account.gl_journal_entries.create(....)
# Journal Line (x2)
gle.gl_journal_lines.create(....)
gle.gl_journal_lines.create(....)
end
# return something based on success/failure of transaction
...
Run Code Online (Sandbox Code Playgroud) 我有这样的事情:
class Vehicle
def self.set_color(input)
if %w{blue red green}.include?(input)
input
else
raise "Bad color"
end
end
end
class Car < Vehicle
def make_car
begin
my_color = Vehicle.set_color("orange")
rescue
puts "you screwed the pooch"
end
end
end
class CarTest < Test::Unit::TestCase
def test_number_one
c = Car.new
c.make_car
end
end
Run Code Online (Sandbox Code Playgroud)
但出于某种原因,我的测试是提高异常并停止执行而不是捕获并输出"你搞砸了小狗".知道为什么会这样,以及如何解决它?
谢谢!
我正在检查日志文件中是否有任何错误消息.如果在日志文件中找到错误消息,那么我使用'raise'语句来报告创建.然而,ruby在执行'raise'语句后停止运行,即使我使用'rescue'.我希望脚本在'raise'语句后继续检查下一个日志文件是否有错误,但不确定如何.任何帮助,将不胜感激!
logs_all = s.sudo "egrep -i '#{error_message}' #{log_file}"
logs_all.each do |hostname, logs|
unless logs.empty?
puts line, "Unhappy logs on #{hostname}", line, logs
happy = false
end
begin
raise "Unhappy logs found! in #{log_file}" unless happy
rescue raise => error
puts error.message
end
end
Run Code Online (Sandbox Code Playgroud) 我正在调试一个问题simple_token_authentication,我修改了https://github.com/gonzalo-bulnes/simple_token_authentication/blob/master/lib/simple_token_authentication/sign_in_handler.rb#L7中的一些代码:
def sign_in(controller, record, *args)
begin
puts "=== TRACE 1"
integrate_with_devise_trackable!(controller)
puts "=== TRACE 2"
controller.send(:sign_in, record, *args)
puts "=== TRACE 3"
rescue Exception => e
puts "=== TRACE 4"
ensure
puts "=== TRACE 5"
end
end
Run Code Online (Sandbox Code Playgroud)
输出:
Started GET "/projects" for ::1 at 2016-04-18 18:35:22 +0800
ActiveRecord::SchemaMigration Load (0.1ms) SELECT "schema_migrations".* FROM "schema_migrations"
Processing by ProjectsController#index as JSON
Parameters: {"project"=>{}}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."email" = ? ORDER BY "users"."id" ASC …Run Code Online (Sandbox Code Playgroud)