问题
So I'm parsing data from twitter api in rails using the twitter library, and sometimes the response from api might be like this:
{
error: "Invalid parameter"
}
And the model will raise an exception, right now I'm silently catch it and put the error.message into the log, how do I pass this exception to the controller so I can display it on the view? Thanks.
UPDATE:
The error is likely to happen because I'm allowing my customer to build queries, and they might put advanced queries like "https://search.twitter.com/search.json?since_id=1&&q=near:NYC%20within:15mi"
which is supported by the twitter webpage but not by it's API. So I want to catch these kinda of error and display a flash message so the user can have some feedback.
回答1:
I guess you could an attr_accessor
. Something like twitter_errors
.
In your model:
attr_accessor :twitter_errors
begin
#your twitter code here
rescue
self.twitter_errors = "whatever"
end
And in your controller, set the flash if @model.twitter_errors
isn't empty.
回答2:
The typical way is to use ActiveModel::Errors.
ActiveRecord uses this mixin extensively for validations. So in an ActiveRecord
object you have access to errors.add(:base, TwitterError.to_s)
. You can use this to set the error when it is caught. And then you should be able to access it via the controller/view using ar_object.errors
.
(There are already some helpers for displaying errors like this the docs have much more info)
来源:https://stackoverflow.com/questions/6932965/rails-how-to-handle-error-and-exceptions-in-model