从Twitter宝石救援 [英] Rescuing from Twitter Gem
问题描述
我有一个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
状态更新失败时,我正在尝试营救.我想向用户显示一条即时消息,但是-据我所知:
I'm trying to rescue when the status update fails. I want to display a flash message to the user, but -- this is as far as I can seem to get:
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
如何获取错误消息,以便可以通过控制器将其显示给用户?
How do I get the error message so I can display it to my user through the controller?
推荐答案
您可以根据应用程序创建并引发自定义异常.
You can create and throw a custom exception based on the application.
在app/lib/could_not_update_status_error.rb
In 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子句中抢救return false,并将update_status调用包装在if语句中,但是Exceptions是更可靠的解决方案.
Another option would be to do rescue return false in your Twitter::Error clause and wrap the update_status call in an if statement, however Exceptions are a more robust solution.
这篇关于从Twitter宝石救援的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!