开始..救援......救援..确保只是出错?

时间:2016-01-21 16:29:45

标签: ruby-on-rails ruby-on-rails-4

快速提问,开始,救援,确保。以下面的代码为例:

begin
  user = User.new

  # Do stuff with User

  user.save if user.valid?

  # Do other stuff here...

  # ## Error happens here after user has already been saved. ##

  render text: "Success", status: :ok
rescue MyExceptions::MySpecialError => e
  # Do something special here for an error
  # Output errors the user has power to fix themselves
  render text: "You messed up!", status: :bad_request
rescue => e
  # Do something special here for an error the user can't fix
  render text: "Internal Error! See support!", status: :unprocessed_entity
ensure
  # If user was created, destroy them
  user.destroy
end

无论是否发生错误,都要确保运行。有没有办法只在发生错误时才运行user.destroy(或确保)?

提前致谢!

1 个答案:

答案 0 :(得分:0)

ensure中的代码无论是否存在错误都将被执行,这实际上是使用它的好处。

在您的具体情况下,您可以在user.destroy内移动rescue,只有在发生错误时才会运行。