Module: ApiErrorHandler

Defined in:
lib/api_error_handler.rb,
lib/api_error_handler/errors.rb,
lib/api_error_handler/version.rb,
lib/api_error_handler/error_reporter.rb,
lib/api_error_handler/serializers/xml.rb,
lib/api_error_handler/serializers/json.rb,
lib/api_error_handler/error_id_generator.rb,
lib/api_error_handler/serializers/json_api.rb,
lib/api_error_handler/serializers/base_serializer.rb

Defined Under Namespace

Modules: Serializers Classes: Error, ErrorIdGenerator, ErrorReporter, InvalidOptionError, MissingDependencyError

Constant Summary collapse

SERIALIZERS_BY_FORMAT =
{
  json: Serializers::Json,
  json_api: Serializers::JsonApi,
  xml: Serializers::Xml,
}.freeze
SERIALIZER_OPTIONS =
{
  backtrace: false,
}.freeze
CONTENT_TYPE_BY_FORMAT =
{
  json_api: "application/vnd.api+json"
}.freeze
VERSION =
"0.2.0"

Instance Method Summary collapse

Instance Method Details

#handle_api_errors(options = {}) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/api_error_handler.rb', line 26

def handle_api_errors(options = {})
  format = options.fetch(:format, :json)
  error_reporter = ErrorReporter.new(options[:error_reporter])
  serializer_options = SERIALIZER_OPTIONS.merge(
    options.slice(*SERIALIZER_OPTIONS.keys)
  )

  serializer_class = options[:serializer] || SERIALIZERS_BY_FORMAT.fetch(format)
  content_type = options[:content_type] || CONTENT_TYPE_BY_FORMAT[format]
  rescue_from StandardError do |error|
    begin
      status = ActionDispatch::ExceptionWrapper.rescue_responses[error.class.to_s]

      error_id = ErrorIdGenerator.run(options[:error_id])
      error_reporter.report(error, error_id: error_id)

      serializer = serializer_class.new(error, status)
      response_body = serializer.serialize(
        serializer_options.merge(error_id: error_id)
      )

      render(
        serializer.render_format => response_body,
        content_type: content_type,
        status: status
      )
    rescue
      raise error
    end
  end
end