# 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
