在rails控制器中挽救无效日期

时间:2015-01-29 02:17:40

标签: ruby-on-rails ruby exception-handling rescue

我在控制器中有这个:

pickuptime = params[:appointment][:pickuptime]
pickuptime = DateTime.strptime(pickuptime, "%m/%d/%Y %l:%M %p %Z")

我希望rescue如果DateTime.strptime重新发送Invalid Date错误,并将其重定向回上一页,并显示“无效日期”消息。我怎么能做到这一点?

我正在使用Ruby 2.1.2和Rails 4.1.4。谢谢!

1 个答案:

答案 0 :(得分:9)

您可以在控制器中执行此操作:

begin
  pickuptime = params[:appointment][:pickuptime]
  pickuptime = DateTime.strptime(pickuptime, "%m/%d/%Y %l:%M %p %Z")
rescue ArgumentError => e
  flash[:error] = e.message
  redirect_to :back
  return
end

Invalid Date错误应该是带有所需消息的ArgumentError异常。