Skip to content

Commit 2ef3c18

Browse files
authored
Twilio delivery method allows Notifier to handle errors (#444)
* Twilio delivery method allows Notifier to handle errors * Add an example how to handle Twilio error
1 parent 2a3dbb0 commit 2ef3c18

File tree

3 files changed

+46
-2
lines changed

3 files changed

+46
-2
lines changed

docs/delivery_methods/twilio_messaging.md

+17
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,23 @@ deliver_by :twilio_messaging do |config|
3838
end
3939
```
4040

41+
## Error Handling
42+
43+
```ruby
44+
deliver_by :twilio_messaging do |config|
45+
config.error_handler = lambda do |twilio_error_response|
46+
error_hash = JSON.parse(twilio_error_response.body)
47+
case error_hash["code"]
48+
when 21211
49+
# The 'To' number is not a valid phone number.
50+
# Write your error handling code
51+
else
52+
raise "Unhandled Twilio error: #{error_hash}"
53+
end
54+
end
55+
end
56+
```
57+
4158
## Options
4259

4360
* `json` - *Optional*

lib/noticed/delivery_methods/twilio_messaging.rb

+6
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,12 @@ module DeliveryMethods
33
class TwilioMessaging < DeliveryMethod
44
def deliver
55
post_request url, basic_auth: {user: account_sid, pass: auth_token}, form: json.stringify_keys
6+
rescue Noticed::ResponseUnsuccessful => exception
7+
if exception.response.code.start_with?("4") && config[:error_handler]
8+
notification.instance_exec(exception.response, &config[:error_handler])
9+
else
10+
raise
11+
end
612
end
713

814
def json

test/delivery_methods/twilio_messaging_test.rb

+23-2
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
class TwilioMessagingTest < ActiveSupport::TestCase
44
setup do
55
@delivery_method = Noticed::DeliveryMethods::TwilioMessaging.new
6-
set_config(
6+
@config = {
77
account_sid: "acct_1234",
88
auth_token: "token",
99
json: -> {
@@ -13,7 +13,8 @@ class TwilioMessagingTest < ActiveSupport::TestCase
1313
Body: "Hello world"
1414
}
1515
}
16-
)
16+
}
17+
set_config(@config)
1718
end
1819

1920
test "sends sms" do
@@ -38,6 +39,26 @@ class TwilioMessagingTest < ActiveSupport::TestCase
3839
end
3940
end
4041

42+
test "passes error to notification instance if error_handler is configured" do
43+
@delivery_method = Noticed::DeliveryMethods::TwilioMessaging.new(
44+
"delivery_method_name",
45+
noticed_notifications(:one)
46+
)
47+
48+
error_handler_called = false
49+
@config[:error_handler] = lambda do |twilio_error_message|
50+
error_handler_called = true
51+
end
52+
set_config(@config)
53+
54+
stub_request(:post, "https://api.twilio.com/2010-04-01/Accounts/acct_1234/Messages.json").to_return(status: 422)
55+
assert_nothing_raised do
56+
@delivery_method.deliver
57+
end
58+
59+
assert(error_handler_called, "Handler is called if status is 4xx")
60+
end
61+
4162
private
4263

4364
def set_config(config)

0 commit comments

Comments
 (0)