gpt4 book ai didi

ruby-on-rails-3 - 在 Rails Controller 中呈现和重新引发异常

转载 作者:行者123 更新时间:2023-12-05 02:24:48 24 4
gpt4 key购买 nike

我在 Rails 中创建一个 API,我遇到了这样一种情况,我想通过向用户传递一些带有错误消息的 JSON 来提醒他们发生了一些不好的事情。但是,我也想重新提出异常,以便 Airbrake(以前称为 Hoptoad)仍会捕获错误并通知我们,以便我们可以进一步调查问题。

我目前正在捕获这样的错误:

begin
if @myobject.update_attributes(:foo => "bar")
render :json => @myobject, :status => :ok
else
render :json => @myobject.errors, :status => :unprocessable_entity
end
rescue Exception => e
render :json => { :errors => { :message => "Uh oh! Something went wrong." } }
raise e
end

问题是我的客户端从来没有收到 JSON 消息,因为 raise e 阻止它呈现并向它发送一个通用的 500 错误。

我应该如何解决这个问题?

[我的解决方案]

正如下面 Jordan 所建议的,只要我捕获到异常,我只需在我的代码中调用 notify_airbrake(ex)。但是,我通过将以下内容添加到我的 ApplicationController 中对其进行了一些抽象,以便将来我可以轻松地从 Airbrake 更改为其他内容:

class ApplicationController < ActionController::Base
...

def notify_exception_service(ex)
notify_airbrake(ex)
end

...
end

因此,我只是调用 notify_exception_service(ex) 而不是 notify_airbrake(ex)

最佳答案

来自 Airbrake gem documentation :

If you want to log arbitrary things which you've rescued yourself from a controller, you can do something like this:

rescue => ex
notify_airbrake(ex)

flash[:failure] = 'Encryptions could not be rerouted, try again.'
end

The #notify_airbrake call will send the notice over to Airbrake for later analysis. While in your controllers you use the notify_airbrake method, anywhere else in your code, use Airbrake.notify.

您不必为了在 Airbrake 中记录它而重新引发异常。

关于ruby-on-rails-3 - 在 Rails Controller 中呈现和重新引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8887366/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com