【问题标题】:Rails 6 proper rescue from error and fetch error messageRails 6 从错误中正确救援并获取错误消息
【发布时间】:2021-11-23 07:10:45
【问题描述】:

在我的 Rails 6 应用程序中,我想处理外部 API 返回错误并将其传递给 Failure 方法(它是 dry-monad method)的情况。

def call
  response = api.check_applicant_status(id: applicant_id, options: options)
rescue Errors::BadRequestError => e
  e.message

  result(response: response, error: e.message)
end

attr_reader :applicant_id

private

def result(response:, error:)
  if response.present?
    Success(response)
  else
    Failure(error)
  end
end

上述代码仅在发生错误时才有效。在快乐的路径中(会有适当的响应),整个类将从 response 变量(哈希)返回一个结果,甚至不会触及 result 方法。

我认为rescue 应该在每个方法的末尾(这是我猜的约定),但在我的情况下,如果是快乐路径,它会给出undefined local variable or method 'e 的错误。

在发生错误时将错误消息传递给Failure 并将结果(哈希)传递给Success 的正确方法是什么?

【问题讨论】:

    标签: ruby-on-rails ruby monads


    【解决方案1】:

    为什么需要私有方法?假设成功,除非您救援,然后假设错误对吗?

    def call
      response = api.check_applicant_status(id: applicant_id, options: options)
      Success(response)
    rescue Errors::BadRequestError => e
      Failure(e.message)
    end
    

    【讨论】:

    • 我明白你的意思,它会起作用,但如果我在我的应用程序中有这段代码 10 次怎么办?这就是为什么我想将这个东西提取到一个私有方法(它应该是protected btw)——供多个类使用。
    • @mr_muscle 在这种情况下,可以轻松地将逻辑移至所述受保护方法。如果你在复制代码,那么你无论如何都不是在练习 DRY。
    猜你喜欢
    • 1970-01-01
    • 2011-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-25
    • 2013-08-31
    • 1970-01-01
    相关资源
    最近更新 更多