這是CreateSubscription服務類。我把這個邏輯放在服務中,因爲有api調用並且發生了一些數據插入。 (這是簡化版)錯誤處理返回服務中的錯誤對象
這個類基本上是從控制器調用的,我需要在那裏處理錯誤。 然而,問題是如何使用user.erros對象而不是full_messages觸發錯誤,以便我可以迭代錯誤並使用JSON創建錯誤響應。
{ 「錯誤」: 「UUID不能爲空,名稱不能爲空,而電子郵件是無效的」 }
到
{ 「錯誤 「:[{ 」的uuid「:[ 」不能爲空「 ],」 姓名」:[ 「不能爲空」] .. } ] }
服務/ create_subscription.rb
class CreateSubscription
class UserCreateError < StandardError; end
def self.call(plan, user_info:)
subscription = nil
ActiveRecord::Base.transaction do
user = CreateUser.call(user_info)
raise UserCreateError.new(user.errors.full_messages.to_sentence) unless user.valid?
服務/ create_user.rb
class CreateUser
def self.call(payment_info)
uuid = payment_info[:uuid]
name = payment_info[:name]
email = payment_info[:email]
user = User.find_by(uuid: uuid)
return user if user.present?
user = User.create(
uuid: uuid,
name: name,
email: email
)
user
end
end
UPDATE
控制器/ subscriptions_controller.rb
def create
# Some logic ....
rescue CreateSubscription::UserCreateError => e
# TODO: This should be an array, not only each one
render json: { error: e.message }, status: :bad_request
這並不工作。謝謝。不過,我不知道爲什麼它輸出反斜槓「錯誤」:「{:uuid => [\」不能爲空\「]。 – Tosh
您能否將它添加到您的問題如何使用它? – siegy22
已更新。爲每個添加迭代器到箱子,但它基本上輸出JSON格式的錯誤。 – Tosh