2011-12-27 93 views
2

我正在用Twitter gem制作一个简单的Rails应用程序。该应用程序会提示用户从表单选择值中选择值,然后将其放入推文中。由于用户正在从表单中选择值,并且因为有默认值,所以用户(不耐烦地点击“发布到Twitter”按钮)尝试创建重复的推文的可能性很高,这些推文被Twitter禁止如何处理更新操作中的错误(使用Twitter宝石)

Twitter::Error::Forbidden in SessionsController#update

Status is a duplicate.

因此,这个小白正试图建立自己的第一个错误处理程序

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

这可能是一些其他类型的错误正在被抛出,而不是它“粘住”。您需要跟踪错误日志(或使用调试器)以查看抛出(并挽救)了什么异常。您也可以使用多个救援的情况下,以测试各种异常,像这样:

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 
+0

所以在第二个示例中,用户是否收到两条错误消息“出错了”,然后进一步解释“Hey Loser ...”,或者他们是否有单独的错误? – Leahcim 2011-12-28 08:07:02

+0

在第二个示例中,如果client.update(@twit)会抛出一个Twitter :: Error,您将从begin块返回并放入rescue块(因此永远不会执行if/else),您只会得到一个异常。 ... – edwardsharp 2011-12-28 19:22:58