class Particle::Error

Custom error class for rescuing from all Particle errors

@see docs.particle.io/core/api/#introduction-errors

Attributes

response[R]
short_message[R]

Public Class Methods

from_response(response) click to toggle source

Returns the appropriate Particle::Error subclass based on status and response message

@param [Hash] response HTTP response @return [Particle::Error]

# File lib/particle/error.rb, line 12
def self.from_response(response)
  status  = response[:status].to_i
  body    = response[:body].to_s

  if klass =  case status
              when 400      then bad_request_error(body)
              when 401      then Particle::Unauthorized
              when 403      then Particle::Forbidden
              when 404      then Particle::NotFound
              when 408      then Particle::TimedOut
              when 500..599 then Particle::ServerError
              end
    klass.new(response)
  end
end
new(response=nil) click to toggle source
Calls superclass method
# File lib/particle/error.rb, line 28
def initialize(response=nil)
  @response = response
  @short_message = build_short_message
  super(build_error_message)
end

Private Class Methods

bad_request_error(body) click to toggle source
# File lib/particle/error.rb, line 39
def self.bad_request_error(body)
  if body =~ /access token was not found/i
    MissingTokenError
  else
    BadRequest
  end
end

Private Instance Methods

build_error_message() click to toggle source
# File lib/particle/error.rb, line 57
def build_error_message
  return nil if response.nil?

  message =  "#{response[:method].to_s.upcase} "
  message << redact_url(response[:url].to_s) + ": "
  message << "#{response[:status]} - "
  message << "#{response[:body]}"
  message
end
build_short_message() click to toggle source
# File lib/particle/error.rb, line 47
def build_short_message
  if response && response[:body] && response[:body][:error]
    response[:body][:error]
  elsif response && response[:body] && response[:body][:errors]
    response[:body][:errors].join ", "
  else
    self.class.name
  end
end
redact_url(url_string) click to toggle source
# File lib/particle/error.rb, line 67
def redact_url(url_string)
  token = "access_token"
  url_string.gsub!(/#{token}=\S+/, "#{token}=(redacted)") if url_string.include? token
  url_string
end