Class: Easy::Api::Error

Inherits:
Object
  • Object
show all
Defined in:
lib/easy/api/error.rb

Overview

Encapsulates the types of errors that API calls can respond with

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(type, msg = nil) ⇒ Error

Initializes a new error based on the type, with an optional custom message

Parameters:

  • type (Symbol)

    can be :invalid, :unauthorized, :not_found, or :unexpected

  • msg (optional, String) (defaults to: nil)

    a custom error message (see MESSAGES for default message values)



28
29
30
31
# File 'lib/easy/api/error.rb', line 28

def initialize(type, msg=nil)
  @code = self.class.codes[type]
  @message = msg || self.class.messages[type]
end

Instance Attribute Details

#codeObject (readonly)

Returns the value of attribute code.



4
5
6
# File 'lib/easy/api/error.rb', line 4

def code
  @code
end

#messageObject (readonly)

Returns the value of attribute message.



4
5
6
# File 'lib/easy/api/error.rb', line 4

def message
  @message
end

Class Method Details

.codesObject



6
7
8
9
10
11
12
13
# File 'lib/easy/api/error.rb', line 6

def self.codes
  @_codes ||= {
    :invalid      => 400,
    :unauthorized => 401,
    :not_found    => 404,
    :unexpected   => 500
  }
end

.messagesObject



15
16
17
18
19
20
21
22
# File 'lib/easy/api/error.rb', line 15

def self.messages
  @_messages ||= {
    :invalid      => "Invalid request",
    :unauthorized => "Unauthorized request",
    :not_found    => "Resource not found",
    :unexpected   => 'Sorry! An exception has occurred',
  }
end

Instance Method Details

#as_json(options = {}) ⇒ Hash

Used by Rails to parse the error as json

Returns:

  • (Hash)

    a hash containing the error code and message



43
44
45
# File 'lib/easy/api/error.rb', line 43

def as_json(options={})
  to_hash
end

#to_hashHash

Returns the error as a hash

Returns:

  • (Hash)

    a hash containing the error code and message



36
37
38
# File 'lib/easy/api/error.rb', line 36

def to_hash
  {:code => @code, :message => @message}
end

#to_xml(options = {}) ⇒ Hash

Used by Rails to parse the error as xml

Returns:

  • (Hash)

    a hash containing the error code and message



50
51
52
# File 'lib/easy/api/error.rb', line 50

def to_xml(options={})
  to_hash.to_xml(options)
end