0

我有一个tweets_controller

#called when user submits twitter form

def message
          unless current_user
            session[:twitter_message] = params[:twitter_message] #sets the message from the form so it's available for send_tweet in tweet.rb after we pass through omniauth
            redirect_to '/auth/twitter' #redirects to authorize via omniauth/twitter and create the user
          else
            @auth = Authorization.find_by_user_id(current_user)
            Tweet.update_status(@auth, params[:twitter_message])
            redirect_to edit_user_path(current_user), :notice => "Tweet sent."
          end
end

当状态更新失败时,我正在尝试救援。我想向用户显示一条消息,但是 - 这是我所能得到的:

def self.update_status(auth, msg)

     @token = auth.token
     @secret = auth.secret
     @message = msg
     @t = Twitter::Client.new

     Twitter.configure do |config|
       config.consumer_key = '[key]'
       config.consumer_secret = '[secret]'
       config.oauth_token = @token
       config.oauth_token_secret = @secret
       config.gateway = '[gateway_url]'
     end

     ret = @t.update(@message)
     tweet ||= Tweet.create_from_response(ret, auth.id)

    rescue Twitter::Error => e
      logger.error "#{e.message}."
end

如何获取错误消息,以便我可以通过控制器将其显示给我的用户?

4

1 回答 1

1

您可以根据应用程序创建和引发自定义异常。

在 app/lib/could_not_update_status_error.rb

class CouldNotUpdateStatusError < StandardError
end

然后在你的模型中:

rescue Twitter::Error => e
  logger.error "#{e.message}."
  raise CouldNotUpdateStatusError.new("Could not update status")

在你的控制器中

else
  begin
    @auth = Authorization.find_by_user_id(current_user)
    Tweet.update_status(@auth, params[:twitter_message])
    redirect_to edit_user_path(current_user), notice: "Tweet sent."
  rescue CoundNotUpdateStatusError => e
    # Do error stuff
end

另一种选择是在您的 Twitter::Error 子句中执行救援返回 false 并将 update_status 调用包装在 if 语句中,但是异常是一个更强大的解决方案。

于 2011-07-17T21:33:42.670 回答