[英]Rails way to catch and handle exceptions
我正在尋找從服務類中捕獲和處理 rails 應用程序中的異常的最佳方法。
我有一個調用服務 x 的類,如果用戶信息錯誤,服務 x 會返回錯誤。 目前我們處理錯誤並刪除數據庫中先前創建的對象。
class Main
...
error_response = ServiceX.new(hash).run
if error_response
StampRequest.delete(stamp_requests)
raise StampError, error_response[:error]
end
...
end
問題是服務 x 調用了其他幾個服務,包括外部的外部 AWS,目前如果這些服務失敗或導致異常,我不確定處理這些錯誤並將它們傳遞回的最佳方法或“rails 方法”主要類。 目前,例如,如果對 AWS 服務的調用失敗,則主類無法知道這一點。
class ServiceX
...
return error_response unless subscribed_to_price_alert_users_available?(subscribed_to_price_alert_users)
subscribed_to_price_alert_users.each do |user|
PricingMailer.notify(user, user_hash(user)).deliver_later
Sms::PricingSms.new(build_hash(user)).submit
PricingService.new(user, reminder_hash(user)).submit unless reminders?
end
# return nil to indicate success
nil
end
...
end
如果外部服務失敗,我想從數據庫中刪除StampRequests
,如果出現用戶錯誤,我會這樣做。
為成功傳遞nil
不是最好/正確的方法。 希望下面的代碼片段可以幫助你。
class Main
...
begin
ServiceX.new(hash).run
rescue StandardError, AWSError => exception
...
StampRequest.delete(stamp_requests)
raise StampError, exception.message
end
end
class ServiceX
...
raise StandardError.new(error_response) unless subscribed_to_price_alert_users_available?(subscribed_to_price_alert_users)
# Assuming you have AWS/External service calls in this loop
# Let it raise exception (AWSError), this has to be handled wisely by the caller of this function.
# In this case caller: a fn in Main class, it has rescue block to handle this exception
subscribed_to_price_alert_users.each do |user|
PricingMailer.notify(user, user_hash(user)).deliver_later
Sms::PricingSms.new(build_hash(user)).submit
PricingService.new(user, reminder_hash(user)).submit unless reminders?
end
...
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.