Skip to content

Commit

Permalink
Code cleanup + better docs for exceptions handling
Browse files Browse the repository at this point in the history
  • Loading branch information
Sergiusz Woźnicki committed Aug 26, 2014
1 parent cca87ae commit 5ebcd25
Show file tree
Hide file tree
Showing 6 changed files with 77 additions and 10 deletions.
26 changes: 26 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,26 +34,52 @@ between you and the MangoPay Team.
```ruby
require 'mangopay'


# configuration (not required if Rails generator fired as above)
MangoPay.configure do |c|
c.preproduction = true
c.client_id = 'YOUR_CLIENT_ID'
c.client_passphrase = 'YOUR_CLIENT_PASSWORD'
end


# get some user by id
john = MangoPay::User.fetch(john_id) # => {FirstName"=>"John", "LastName"=>"Doe", ...}


# update some of his data
MangoPay::NaturalUser.update(john_id, {'LastName' => 'CHANGED'}) # => {FirstName"=>"John", "LastName"=>"CHANGED", ...}


# get all users (with pagination)
pagination = {'page' => 1, 'per_page' => 8} # get 1st page, 8 items per page
users = MangoPay::User.fetch(pagination) # => [{...}, ...]: list of 8 users data hashes
pagination # => {"page"=>1, "per_page"=>8, "total_pages"=>748, "total_items"=>5978}


# get John's bank accounts
accounts = MangoPay::BankAccount.fetch(john_id) # => [{...}, ...]: list of accounts data hashes (10 per page by default)


# errors handling
begin
MangoPay::NaturalUser.create({})
rescue MangoPay::ResponseError => ex

ex # => #<MangoPay::ResponseError: One or several required parameters are missing or incorrect. [...] FirstName: The FirstName field is required. LastName: The LastName field is required. Nationality: The Nationality field is required.>

ex.details # => {
# "Message"=>"One or several required parameters are missing or incorrect. [...]",
# "Type"=>"param_error",
# "Id"=>"5c080105-4da3-467d-820d-0906164e55fe",
# "Date"=>1409048671.0,
# "errors"=>{
# "FirstName"=>"The FirstName field is required.",
# "LastName"=>"The LastName field is required.", ...},
# "Code"=>"400",
# "Url"=>"/v2/.../users/natural"
# }
end
```

### Tests
Expand Down
2 changes: 1 addition & 1 deletion lib/mangopay.rb
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ def request(method, url, params={}, filters={}, headers = request_headers, befor


unless res.is_a?(Net::HTTPOK)
fail MangoPay::ResponseError.new(uri, res.code, data)
raise MangoPay::ResponseError.new(uri, res.code, data)

This comment has been minimized.

Copy link
@seuros

seuros Aug 26, 2014

Contributor

fail and raise are aliases. Use raise when you are going to catch it again.

end

# copy pagination info if any
Expand Down
36 changes: 35 additions & 1 deletion lib/mangopay/errors.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,51 @@ class Error < StandardError

# Thrown from any MangoPay API call whenever
# it returns response with HTTP code != 200.
# Check @details hash for further info.
#
# Two example exceptions with details:
#
# #<MangoPay::ResponseError:
# One or several required parameters are missing or incorrect. [...]
# Email: The Email field is required.>
# {"Message"=>"One or several required parameters are missing or incorrect.
# An incorrect resource ID also raises this kind of error.",
# "Type"=>"param_error",
# "Id"=>"66936e92-3f21-4a35-b6cf-f1d17c2fb6e5",
# "Date"=>1409047252.0,
# "errors"=>{"Email"=>"The Email field is required."},
# "Code"=>"400",
# "Url"=>"/v2/sdk-unit-tests/users/natural"}
#
# #<MangoPay::ResponseError: Internal Server Error>
# {"Message"=>"Internal Server Error",
# "Type"=>"other",
# "Id"=>"7bdc5c6f-2000-4cd3-96f3-2a3fcb746f07",
# "Date"=>1409047251.0,
# "errors"=>nil,
# "Code"=>"500",
# "Url"=>"/v2/sdk-unit-tests/payins/3380640/refunds"}
class ResponseError < Error

attr_reader :request_url, :code, :details

def initialize(request_url, code, details)
@request_url, @code, @details = request_url, code, details

@details['Code'] = code
@details['Url'] = request_url.request_uri

super(message) if message
end

def message; @details['Message']; end
def type; @details['Type']; end
def errors; @details['errors']; end

def message;
msg = @details['Message']
msg += errors.sort.map {|k,v| " #{k}: #{v}"}.join if (errors && errors.is_a?(Hash))
msg
end

end
end
2 changes: 1 addition & 1 deletion lib/mangopay/resource.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ def class_name

def url(id = nil)
if self == Resource
fail NotImplementedError.new('Resource is an abstract class. Do not use it directly.')
raise NotImplementedError.new('Resource is an abstract class. Do not use it directly.')
end
if id
"#{MangoPay.api_path}/#{CGI.escape(class_name.downcase)}s/#{CGI.escape(id.to_s)}"
Expand Down
4 changes: 0 additions & 4 deletions spec/mangopay/shared_resources.rb
Original file line number Diff line number Diff line change
Expand Up @@ -175,10 +175,6 @@ def wallets_reload_and_check_amounts(wlt1, amnt1, wlt2 = nil, amnt2 = nil)
cardExpirationDate: 1214,
cardCvx: 123}
res = Net::HTTP.post_form(URI(cardreg['CardRegistrationURL']), data)
############### TEMP!!!! #######################################################
#pp :post, cardreg['CardRegistrationURL'], data
#pp res, res.body
#puts
raise Exception, [res, res.body] unless (res.is_a?(Net::HTTPOK) && res.body.start_with?('data='))
cardreg['RegistrationData'] = res.body

Expand Down
17 changes: 14 additions & 3 deletions spec/spec_helper.rb
Original file line number Diff line number Diff line change
@@ -1,17 +1,28 @@
require 'mangopay'
require_relative 'mangopay/shared_resources'

require 'fileutils'
require 'pp'

# (re-called once in configuration_spec)
################################################################################
# mangopay test account config (re-called once in configuration_spec)
def reset_mangopay_configuration
MangoPay.configure do |c|
c.preproduction = true
c.client_id = 'sdk-unit-tests'
c.client_passphrase = 'cqFfFrWfCcb7UadHNxx2C9Lo6Djw8ZduLi7J9USTmu8bhxxpju'
c.temp_dir = File.expand_path('../tmp', __FILE__)
require 'fileutils'
FileUtils.mkdir_p(c.temp_dir) unless File.directory?(c.temp_dir)
end
end
reset_mangopay_configuration


################################################################################
# uncomment it for logging all http calls in tests
#require 'http_logger'
#require 'logger'
#HttpLogger.logger = Logger.new(STDOUT)
#HttpLogger.colorize = true
#HttpLogger.log_headers = false
#HttpLogger.log_request_body = true
#HttpLogger.log_response_body = true

0 comments on commit 5ebcd25

Please sign in to comment.