Rails how to handle error and exceptions in model
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.
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.
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)
精彩评论