Rails 外部服务异常处理

Rails External Service Exception Handling

我正在将我的应用程序连接到第三方 API 以拉取和推送数据。我想做的一件事是实施一些异常处理,这样如果 API 出现问题,我的用户将收到相关的错误消息。

我有一个show action,主要调用里面的第三方服务。我已将服务包装在开始救援块中。我收到以下错误:

Render and/or redirect were called multiple times in this action.

我的表演动作是这样的

def show
  begin
    client = FooBarRest::Client.new
    [API Request Code Here]
  rescue => e
    Rails.logger.error { "#{e.message} #{e.backtrace.join("\n")}" }
    redirect_to signing_error_path
  end
  render_wizard
end

我知道我有两个 renders/redirects(render_wizard 是为了满足向导的要求)发生在块中 - 但我不确定如何重定向到 signing_error_path任何其他方式。

我有一个错误控制器和用于处理 404、500 的视图 etc:class

ErrorsController < ApplicationController

  def not_found
  end 

  def unavailable
  end 

  def internal_error
  end

  def unauthorized_access
  end

  def signing_error
  end

end

相应的视图在 views/errors 文件夹中。 如果我当前的 show 方法引发异常,我如何显示 signing_error 视图?

据我观察,您的整个代码都在 begin rescue 块中

在那种情况下,我建议稍微重写此方法并引入方法级救援块

def show
 call_api....

 render_wizard # will be called only if no error was thrown, so you will not receive any doble render errors any more

rescue => error #of course multiple rescues are allowed for different type of errors
  loger.error(error.message)

  redirect_to signing_error_path

end

如果在 redirect_to

上添加 and return,则可以按原样使用代码

From the API docs

If you need to redirect on the condition of something, then be sure to add “and return” to halt execution.

或者,您可以将 render_wizard 调用放在 begin 块内,就在 rescue => e

之前