Class: ErrorNormalizer::Error

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

Overview

Struct which makes cosmetic normalization on calling either #to_hash or #to_json.

Translates message with path via i18n if corresponding options is passed (see #initialize).

Provides case equality check (Error.===) to support plain Hash structs.

Examples:

Error.new('not_plausible', message: "can't recognize your phone", path: 'user.phone')
Error.new('not_authorized').to_hash
#=> { key: 'not_authorized', message: 'not authorized', type: 'params', payload: {} }

# case equality works with hashes
err = { key: 'err', message: 'err', type: 'custom', payload: {} }
message =
  case err
  when Error
    'YEP'
  else
    'NOPE'
  end
puts message #=> 'YEP'

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(error_key, message: nil, type: 'params', i18n_messages: nil, **payload) ⇒ Error

Returns a new instance of Error.



31
32
33
34
35
36
37
38
# File 'lib/error_normalizer/error.rb', line 31

def initialize(error_key, message: nil, type: 'params', i18n_messages: nil, **payload)
  @key = error_key
  @message = message
  @type = type
  @payload = payload
  @i18n_messages =
    i18n_messages.nil? ? ErrorNormalizer.config.i18n_messages : i18n_messages
end

Class Method Details

.===(other) ⇒ Boolean

Case equality check

Returns:

  • (Boolean)


42
43
44
45
46
47
48
# File 'lib/error_normalizer/error.rb', line 42

def self.===(other)
  return true if other.is_a?(Error)
  return false unless other.is_a?(Hash)

  h = other.transform_keys(&:to_s)
  h.key?('key') && h.key?('message') && h.key?('payload') && h.key?('type')
end

Instance Method Details

#full_messageString

Translate message with path via i18n. Delegates path translation to SchemaPathTranslator.

Returns:

  • (String)


53
54
55
56
57
58
59
60
# File 'lib/error_normalizer/error.rb', line 53

def full_message
  return message unless @i18n_messages && @type == 'params'

  path = payload[:path]
  return if path.nil?

  translate_path(path)
end

#to_hashHash

Returns error Hash representation.

Returns:

  • (Hash)

    error Hash representation



63
64
65
66
67
68
69
70
# File 'lib/error_normalizer/error.rb', line 63

def to_hash
  {
    key: @key,
    message: full_message,
    payload: payload,
    type: @type
  }
end

#to_jsonString

Returns error JSON string representation.

Returns:

  • (String)

    error JSON string representation



73
74
75
# File 'lib/error_normalizer/error.rb', line 73

def to_json
  to_hash.to_json
end