Rails如何处理模型中的错误和异常 [英] Rails how to handle error and exceptions in model

查看:100
本文介绍了Rails如何处理模型中的错误和异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在使用twitter库从rails中的twitter api解析数据,有时api的响应可能是这样的:

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"
}

该模型将引发一个异常,现在我默默地捕获它并将error.message放入日志中,如何将这个异常传递给控制器​​,以便可以在视图上显示它?谢谢.

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.

更新: 该错误很可能发生,因为我允许我的客户建立查询,并且他们可能会输入高级查询,例如"https://search.twitter.com/search.json?since_id=1&&q=near:NYC%20within:15mi",它受twitter网页的支持,但不受其API的支持.因此,我想捕获这些错误并显示Flash消息,以便用户获得一些反馈.

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.

推荐答案

我想您可以使用attr_accessor.类似于twitter_errors.

I guess you could an attr_accessor. Something like twitter_errors.

在您的模型中:

attr_accessor :twitter_errors

begin
  #your twitter code here
rescue
  self.twitter_errors = "whatever"
end

如果@model.twitter_errors不为空,则在控制器中设置闪光灯.

And in your controller, set the flash if @model.twitter_errors isn't empty.

这篇关于Rails如何处理模型中的错误和异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆