Ruby on Rails:从模型传递异常对象
坦白说,我知道标题中的内容可能是不可能的,但我想不出更好的东西。
我的问题是我没有使用 ActiveRecord 来获取/保存数据,而是通过 Web 服务使用一些专用 api。因此,我需要处理来自它的一些异常(例如发送邮件),但我想在模型中执行此操作以避免代码中的冗余。到目前为止,我想到的唯一想法是针对此 Web 服务的某些响应引发异常,以在应用程序控制器中生成正确的操作。不幸的是,我的操作之一是发送包含来自生成错误的网络服务的请求和响应的电子邮件。问题是,如何将它们传递给控制器?
Frankly I know that what stands in the title is probably impossible but I couldn't come up with something better.
My problem is that I'm not using ActiveRecord to get/save data but some dedicated api via webservice. As such I need to handle some exceptions coming from it (e.g. send mails) but I want to do it in the model to avoid redundancy in the code. By now the only idea that I've come up with is raising exceptions for certain responses from this webservice to generate proper actions in the application controller. Unfortunately one of my actions is to send emails with request and responses from webservice which generated the error. The question is, how can I pass them to the controller?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一般来说,使用异常来处理程序流被认为是不好的做法(但是哦,太方便了!=P)。
与其尝试显式地将控制从模型转移到控制器,不如将块传递到模型中,并使用 Yield 来执行该块。这样,当模型希望运行时,您可以在模型中执行控制器中的代码。
下面是将代码传递到函数中的示例,并显示此代码块仍然可以从调用者访问变量(hello == "world" 从调用者的堆栈空间内,但从函数内部运行)。对我来说感觉更干净。
再见只是为了表明,一旦函数结束,函数中定义的变量就会从堆栈中弹出。
In general, using exceptions to handle program flow is considered bad practice (but oh so handy! =P).
Instead of trying to explicitly transfer control from the model to the controller, how about passing a block into the model, and using yield to execute that block. In that way, you can have code from the controller being executed in the model, when the model wants it to be run.
Here's an example of passing code into a function, and showing that this code block can still access variables from the caller (hello == "world" from within the caller's stack space, but was run from inside the function). It feels cleaner to me.
goodbye is there just to show that variables defined within the function get popped off the stack once the function ends.