Module: JsonapiErrorsHandler

Defined in:
lib/jsonapi_errors_handler.rb,
lib/jsonapi_errors_handler/errors.rb,
lib/jsonapi_errors_handler/version.rb,
lib/jsonapi_errors_handler/error_mapper.rb,
lib/jsonapi_errors_handler/configuration.rb,
lib/jsonapi_errors_handler/errors/invalid.rb,
lib/jsonapi_errors_handler/error_serializer.rb,
lib/jsonapi_errors_handler/errors/forbidden.rb,
lib/jsonapi_errors_handler/errors/not_found.rb,
lib/jsonapi_errors_handler/keys_stringifier.rb,
lib/jsonapi_errors_handler/errors/unauthorized.rb,
lib/jsonapi_errors_handler/errors/standard_error.rb

Overview

Allows to handle ruby errors and return the serialized JSON:API output

Defined Under Namespace

Modules: Errors Classes: Configuration, ErrorMapper, ErrorSerializer, KeysStringifier

Constant Summary collapse

PREDEFINED_HASH =
{
  'JsonapiErrorsHandler::Errors::Invalid' =>
    'JsonapiErrorsHandler::Errors::Invalid',
  'JsonapiErrorsHandler::Errors::Forbidden' =>
    'JsonapiErrorsHandler::Errors::Forbidden',
  'JsonapiErrorsHandler::Errors::NotFound' => '
    JsonapiErrorsHandler::Errors::NotFound',
  'JsonapiErrorsHandler::Errors::Unauthorized' =>
    'JsonapiErrorsHandler::Errors::Unauthorized'
}.freeze
VERSION =
'0.6.0'

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.configure(&block) ⇒ Object



59
60
61
# File 'lib/jsonapi_errors_handler.rb', line 59

def self.configure(&block)
  Configuration.instance.configure(&block)
end

.included(base) ⇒ Object



23
24
25
26
27
# File 'lib/jsonapi_errors_handler.rb', line 23

def self.included(base)
  base.class_eval do
    ErrorMapper.map_errors!(PREDEFINED_HASH)
  end
end

Instance Method Details

#handle_error(error) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/jsonapi_errors_handler.rb', line 29

def handle_error(error)
  log_error(error) if respond_to?(:log_error)
  # Handle every error which inherits from
  # JsonapiErrorsHandler::Errors::StandardError
  #
  if JsonapiErrorsHandler::ErrorMapper.mapped_error?(error.class.superclass.to_s)
    return render_error(error)
  end

  mapped = ErrorMapper.mapped_error(error)
  mapped ? render_error(mapped) : handle_unexpected_error(error)
end

#handle_unexpected_error(error) ⇒ Object



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

def handle_unexpected_error(error)
  config = JsonapiErrorsHandler::Configuration.instance
  raise error unless config.handle_unexpected?

  notify_handle_unexpected_error(error) if respond_to?(:notify_handle_unexpected_error)

  render_error(::JsonapiErrorsHandler::Errors::StandardError.new)
end

#render_error(error) ⇒ Object



51
52
53
54
55
56
57
# File 'lib/jsonapi_errors_handler.rb', line 51

def render_error(error)
  render(
    json: ::JsonapiErrorsHandler::ErrorSerializer.new(error),
    status: error.status,
    content_type: Configuration.instance.content_type
  )
end