module Aws::Errors::DynamicErrors

This module is mixed into another module, providing dynamic error classes. Error classes all inherit from {ServiceError}.

# creates and returns the class
Aws::S3::Errors::MyNewErrorClass

Since the complete list of possible AWS errors returned by services is not known, this allows us to create them as needed. This also allows users to rescue errors by class without them being concrete classes beforehand.

@api private

Public Class Methods

extended(submodule) click to toggle source
# File lib/aws-sdk-core/errors.rb, line 66
def self.extended(submodule)
  submodule.instance_variable_set("@const_set_mutex", Mutex.new)
  submodule.const_set(:ServiceError, Class.new(ServiceError))
end

Public Instance Methods

const_missing(constant) click to toggle source
# File lib/aws-sdk-core/errors.rb, line 71
def const_missing(constant)
  set_error_constant(constant)
end
error_class(error_code) click to toggle source

Given the name of a service and an error code, this method returns an error class (that extends {ServiceError}.

Aws::S3::Errors.error_class('NoSuchBucket').new
#=> #<Aws::S3::Errors::NoSuchBucket>

@api private

# File lib/aws-sdk-core/errors.rb, line 82
def error_class(error_code)
  constant = error_class_constant(error_code)
  if error_const_set?(constant)
    const_get(constant)
  else
    set_error_constant(constant)
  end
end

Private Instance Methods

error_class_constant(error_code) click to toggle source

Convert an error code to an error class name/constant. This requires filtering non-safe characters from the constant name and ensuring it begins with an uppercase letter. @param [String] error_code @return [Symbol] Returns a symbolized constant name for the given

`error_code`.
# File lib/aws-sdk-core/errors.rb, line 99
def error_class_constant(error_code)
  constant = error_code.to_s
  constant = constant.gsub(/https?:.*$/, '')
  constant = constant.gsub(/[^a-zA-Z0-9]/, '')
  constant = 'Error' + constant unless constant.match(/^[a-z]/i)
  constant = constant[0].upcase + constant[1..-1]
  constant.to_sym
end
error_const_set?(constant) click to toggle source
# File lib/aws-sdk-core/errors.rb, line 121
def error_const_set?(constant)
  # Purposefully not using #const_defined? as that method returns true
  # for constants not defined directly in the current module.
  constants.include?(constant.to_sym)
end
set_error_constant(constant) click to toggle source
# File lib/aws-sdk-core/errors.rb, line 108
def set_error_constant(constant)
  @const_set_mutex.synchronize do
    # Ensure the const was not defined while blocked by the mutex
    if error_const_set?(constant)
      const_get(constant)
    else
      error_class = Class.new(const_get(:ServiceError))
      error_class.code = constant.to_s
      const_set(constant, error_class)
    end
  end
end