Return meaningful text from bandwidth errors

Stephen Paul Weber created

Change summary

lib/bandwidth_error.rb | 24 ++++++++++++++++++++++++
sgx-bwmsgsv2.rb        | 18 +++++++++---------
test/test_component.rb |  6 +++++-
3 files changed, 38 insertions(+), 10 deletions(-)

Detailed changes

lib/bandwidth_error.rb 🔗

@@ -0,0 +1,24 @@
+# frozen_string_literal: true
+
+class BandwidthError < StandardError
+	attr_reader :code
+
+	def self.for(http_code, body)
+		parsed_body = JSON.parse(body) rescue nil
+		if parsed_body.is_a?(Hash)
+			new(
+				http_code,
+				parsed_body["description"].to_s.strip + " " +
+				(parsed_body.fetch("fieldErrors", []))
+					.map { |err| err["description"] }.join(" ")
+			)
+		else
+			new(http_code, "Error #{http_code}")
+		end
+	end
+
+	def initialize(code, msg)
+		super(msg)
+		@code = code
+	end
+end

sgx-bwmsgsv2.rb 🔗

@@ -35,6 +35,7 @@ require 'log4r'
 
 require 'em_promise'
 
+require_relative 'lib/bandwidth_error'
 require_relative 'lib/registration_repo'
 
 Sentry.init
@@ -235,7 +236,9 @@ module SGXbwmsgsv2
 					http
 				end
 			else
-				EMPromise.reject(http.response_header.status)
+				EMPromise.reject(
+					BandwidthError.for(http.response_header.status, http.response)
+				)
 			end
 		}
 	end
@@ -294,10 +297,9 @@ module SGXbwmsgsv2
 			)),
 			{'Content-Type' => 'application/json'},
 			[201]
-		).catch {
-			# TODO: add text; mention code number
+		).catch { |e|
 			EMPromise.reject(
-				[:cancel, 'internal-server-error']
+				[:cancel, 'internal-server-error', e.message]
 			)
 		}
 	end
@@ -603,18 +605,16 @@ module SGXbwmsgsv2
 					phone_num
 				)
 			}
-		}.catch { |e|
-			EMPromise.reject(case e
+		}.catch_only(BandwidthError) { |e|
+			EMPromise.reject(case e.code
 			when 401
 				# TODO: add text re bad credentials
 				[:auth, 'not-authorized']
 			when 404
 				# TODO: add text re number not found or disabled
 				[:cancel, 'item-not-found']
-			when Integer
-				[:modify, 'not-acceptable']
 			else
-				e
+				[:modify, 'not-acceptable']
 			end)
 		}
 	end

test/test_component.rb 🔗

@@ -66,7 +66,10 @@ class ComponentTest < Minitest::Test
 			text: "a"*4096,
 			applicationId: nil,
 			tag: " "
-		}).to_return(status: 400)
+		}).to_return(status: 400, body: JSON.dump(
+			description: "Bad text.",
+			fieldErrors: [{ description: "4096 not allowed" }]
+		))
 
 		m = Blather::Stanza::Message.new("+15551234567@component", "a"*4096)
 		m.from = "test@example.com"
@@ -80,6 +83,7 @@ class ComponentTest < Minitest::Test
 		error = stanza.find_first("error")
 		assert_equal "cancel", error["type"]
 		assert_equal "internal-server-error", xmpp_error_name(error)
+		assert_equal "Bad text. 4096 not allowed", xmpp_error_text(error)
 	end
 	em :test_message_too_long