randomor
randomor

Reputation: 5663

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.

Upvotes: 3

Views: 3972

Answers (2)

diedthreetimes
diedthreetimes

Reputation: 4115

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)

Upvotes: 2

apneadiving
apneadiving

Reputation: 115531

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.

Upvotes: 4

Related Questions