我正在使用Twitter gem创建一个简单的Rails应用程序。该应用程序会提示用户从表单选择中选择值,然后将这些值放入推文中。因为用户正在从表单选择中选择值,并且因为存在默认值,所以用户(不耐烦地点击“发布到推特”按钮)将很有可能尝试创建重复的推文,这是Twitter禁止的。
Twitter :: Error :: SessionsController中禁止#update
状态是重复的。
因此,这个菜鸟正试图创建他的第一个错误处理程序
def update
@twit = "@TwitterUser #{params[:wants]} to go to #{params[:place]} "
begin
client.update(@twit)
redirect_to show_path, :notice => "' ' + #{params[:wants] + ' ' + params[:place] has been tweeted}"
rescue Exception
redirect_to show_path, :notice => "Hey Loser, Twitter says you cannot post same twice"
end
end
问题,有时当我不连续两次发布相同的消息时,它会显示错误消息。我想知道错误信息是否以某种方式粘贴,或者我是否以这样的方式编写了操作?
额外这是我第一次尝试包含错误消息,我不知道我是做对还是错,或者可以做得更好。如果您对此代码的位置有任何提示...非常感谢。例如,我有几个表单/操作可能会引发相同的错误,所以我可以使用DRY技术吗?
答案 0 :(得分:0)
可能会抛出一些其他类型的错误,而不是它“坚持”。您需要跟踪错误日志(或使用调试器)以查看抛出(和获救)的异常。您还可以使用多个救援案例来测试各种异常,例如:
begin
client.update(@twit)
redirect_to show_path, :notice => "' ' + #{params[:wants] + ' ' + params[:place] has been tweeted}"
rescue Twitter::Error
redirect_to show_path, :notice => "Hey Loser, Twitter says you cannot post same twice"
rescue Exception
puts "some other error happened!"
end
处理错误的另一个选择是进行分配,评估和引发任何异常,如下所示:
begin
response = client.update(@twit)
if !response
raise "something went wrong!"
else
redirect_to show_path, :notice => "' ' + #{params[:wants] + ' ' + params[:place] has been tweeted}"
end
rescue Exception
redirect_to show_path, :notice => "Hey Loser, Twitter says you cannot post same twice"
end