Class: Response::SendGridWebApi

Inherits:
Middleware
  • Object
show all
Defined in:
lib/middlewares/sendgrid_response.rb

Instance Method Summary collapse

Instance Method Details

#call(env) ⇒ Object



34
35
36
37
38
39
# File 'lib/middlewares/sendgrid_response.rb', line 34

def call(env)
  @app.call(env).on_complete do
    check_status(env)
    env[:body] = parse_body(env[:body])
  end
end

#check_status(env) ⇒ Object



23
24
25
26
27
28
29
30
31
32
# File 'lib/middlewares/sendgrid_response.rb', line 23

def check_status(env)
  status = env[:status].to_s
  if  status == "403" || status == "401"
    raise AuthenticationError.new(error_message(env[:body]))
  elsif status =~ /^5/
    raise ApiException.new("The API call was unsuccessful. You should retry later.")
  elsif status =~ /^4/
    raise ApiException.new(error_message(env[:body]))
  end
end

#error_message(result) ⇒ Object



10
11
12
13
14
15
16
17
# File 'lib/middlewares/sendgrid_response.rb', line 10

def error_message(result)
  if result[/^[a-z ]+$/i]
    error_msg = result
  else
    error_msg = JSON.parse(result)["error"] || JSON.parse(result)["errors"]
  end
  error_msg.to_s
end

#parse_body(body) ⇒ Object



19
20
21
# File 'lib/middlewares/sendgrid_response.rb', line 19

def parse_body(body)
  JSON.parse(body)
end