0
有關於開始,救援,確保的快速問題。看看下面的代碼,例如:無論開始..救援..救援..確保只有錯誤?
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(或確保)?
在此先感謝!
只需將'user.destroy'放入'rescue'塊。旁註:既然是Rails,你可能需要使用'ActiveRecord :: Base.transaction' –
因此,我必須將user.destroy放在兩個救援塊中?試着讓它幹一點。我繼續使用這種情況下的交易,但只是解釋引用的目的... – Sean
相同[HEAR](http://stackoverflow.com/questions/2191632/begin-rescue-and-ensure-in-ruby) –