Rails how to handle error and exceptions in model

空扰寡人 提交于 2020-01-24 08:55:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!