我在控制器中有这个:
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。谢谢!
答案 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异常。