From f4e8aa9bd160555b5de94a013edcbc09b2be83cf Mon Sep 17 00:00:00 2001 From: Bibek Shrestha Date: Tue, 7 May 2024 18:25:13 -0700 Subject: [PATCH] Twilio delivery method allows Notifier to handle errors --- .../delivery_methods/twilio_messaging.rb | 6 +++++ .../delivery_methods/twilio_messaging_test.rb | 26 +++++++++++++++++-- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/lib/noticed/delivery_methods/twilio_messaging.rb b/lib/noticed/delivery_methods/twilio_messaging.rb index 59ab5f1..a2bada5 100644 --- a/lib/noticed/delivery_methods/twilio_messaging.rb +++ b/lib/noticed/delivery_methods/twilio_messaging.rb @@ -3,6 +3,12 @@ module DeliveryMethods class TwilioMessaging < DeliveryMethod def deliver post_request url, basic_auth: {user: account_sid, pass: auth_token}, form: json.stringify_keys + rescue Noticed::ResponseUnsuccessful => exception + if exception.response.code.start_with?("4") && config[:error_handler] + notification.instance_exec(exception.response, &config[:error_handler]) + else + raise + end end def json diff --git a/test/delivery_methods/twilio_messaging_test.rb b/test/delivery_methods/twilio_messaging_test.rb index 7c1066a..387c510 100644 --- a/test/delivery_methods/twilio_messaging_test.rb +++ b/test/delivery_methods/twilio_messaging_test.rb @@ -3,7 +3,7 @@ class TwilioMessagingTest < ActiveSupport::TestCase setup do @delivery_method = Noticed::DeliveryMethods::TwilioMessaging.new - set_config( + @config = { account_sid: "acct_1234", auth_token: "token", json: -> { @@ -13,7 +13,8 @@ class TwilioMessagingTest < ActiveSupport::TestCase Body: "Hello world" } } - ) + } + set_config(@config) end test "sends sms" do @@ -38,6 +39,27 @@ class TwilioMessagingTest < ActiveSupport::TestCase end end + test "passes error to notification instance if error_handler is configured" do + @delivery_method = Noticed::DeliveryMethods::TwilioMessaging.new( + "delivery_method_name", + noticed_notifications(:one) + ) + + error_handler_called = false + @config[:error_handler] = lambda do |twilio_error_message| + error_handler_called = true + end + set_config(@config) + + + stub_request(:post, "https://api.twilio.com/2010-04-01/Accounts/acct_1234/Messages.json").to_return(status: 422) + assert_nothing_raised do + @delivery_method.deliver + end + + assert(error_handler_called, "Handler is called if status is 4xx") + end + private def set_config(config)