Skip to content

Commit

Permalink
Twilio delivery method allows Notifier to handle errors (#444)
Browse files Browse the repository at this point in the history
* Twilio delivery method allows Notifier to handle errors

* Add an example how to handle Twilio error
  • Loading branch information
bibstha committed May 23, 2024
1 parent 2a3dbb0 commit 2ef3c18
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 2 deletions.
17 changes: 17 additions & 0 deletions docs/delivery_methods/twilio_messaging.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,23 @@ deliver_by :twilio_messaging do |config|
end
```

## Error Handling

```ruby
deliver_by :twilio_messaging do |config|
config.error_handler = lambda do |twilio_error_response|
error_hash = JSON.parse(twilio_error_response.body)
case error_hash["code"]
when 21211
# The 'To' number is not a valid phone number.
# Write your error handling code
else
raise "Unhandled Twilio error: #{error_hash}"
end
end
end
```

## Options

* `json` - *Optional*
Expand Down
6 changes: 6 additions & 0 deletions lib/noticed/delivery_methods/twilio_messaging.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
25 changes: 23 additions & 2 deletions test/delivery_methods/twilio_messaging_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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: -> {
Expand All @@ -13,7 +13,8 @@ class TwilioMessagingTest < ActiveSupport::TestCase
Body: "Hello world"
}
}
)
}
set_config(@config)
end

test "sends sms" do
Expand All @@ -38,6 +39,26 @@ 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)
Expand Down

0 comments on commit 2ef3c18

Please sign in to comment.