Class: JsonapiException

Inherits:
Object
  • Object
show all
Defined in:
lib/jsonapi_exception.rb,
lib/jsonapi_exception/version.rb

Constant Summary collapse

DEFAULT_STATUS =
422
MIME_TYPE =
"application/vnd.api+json".freeze
VERSION =
"0.1.0".freeze

Instance Method Summary collapse

Constructor Details

#initialize(exception, opts = {}) ⇒ JsonapiException

Returns a new instance of JsonapiException.



7
8
9
10
# File 'lib/jsonapi_exception.rb', line 7

def initialize(exception, opts = {})
  @exception = exception
  @opts      = opts
end

Instance Method Details

#as_json(*_) ⇒ Object



55
56
57
58
59
# File 'lib/jsonapi_exception.rb', line 55

def as_json(*_)
  {
    errors: [to_h]
  }
end

#codeObject



37
38
39
# File 'lib/jsonapi_exception.rb', line 37

def code
  opts[:code]
end

#detailObject



25
26
27
# File 'lib/jsonapi_exception.rb', line 25

def detail
  opts.fetch(:detail, exception.message)
end

#for_renderObject



72
73
74
75
76
77
78
# File 'lib/jsonapi_exception.rb', line 72

def for_render
  {
    json:         as_json,
    status:       status,
    content_type: MIME_TYPE
  }
end

#idObject



33
34
35
# File 'lib/jsonapi_exception.rb', line 33

def id
  opts.fetch(:id, exception.object_id)
end


41
42
43
# File 'lib/jsonapi_exception.rb', line 41

def links
  opts[:links]
end

#metaObject



45
46
47
48
49
50
51
52
53
# File 'lib/jsonapi_exception.rb', line 45

def meta
  return opts[:meta] if opts[:meta]
  return unless show_exceptions?
  {
    class:     exception.class.to_s,
    message:   exception.message,
    backtrace: exception.backtrace
  }
end

#statusObject



29
30
31
# File 'lib/jsonapi_exception.rb', line 29

def status
  opts.fetch(:status, DEFAULT_STATUS)
end

#titleObject



12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/jsonapi_exception.rb', line 12

def title
  opts.fetch(:title)
rescue KeyError
  exception
    .class
    .to_s
    .split("::")
    .last
    .scan(/([A-Z][^A-Z]*)/)
    .join(" ")
    .sub(/ (Error|Exception)$/, "")
end

#to_hObject



61
62
63
64
65
66
67
68
69
70
# File 'lib/jsonapi_exception.rb', line 61

def to_h
  {
    title:  title,
    links:  links,
    detail: detail,
    status: status.to_s,
    id:     id,
    code:   code
  }.reject { |_, v| !v }
end