【发布时间】: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