module ApiExceptionManagement

Public Instance Methods

api_error(status: 500, errors: []) click to toggle source
# File lib/concerns/api_exception_management.rb, line 34
def api_error(status: 500, errors: [])
    # puts errors.full_messages if !Rails.env.production? && errors.respond_to?(:full_messages)
    head status && return if errors.empty?
    
    # For retrocompatibility, I try to send back only strings, as errors
    errors_response = if errors.respond_to?(:full_messages) 
        # Validation Errors
        errors.full_messages.join(", ")
    elsif errors.respond_to?(:error)
        # Generic uncatched error
        errors.error
    elsif errors.respond_to?(:exception)
        # Generic uncatchd error, if the :error property does not exist, exception will
        errors.exception
    elsif errors.is_a? Array
        # An array of values, I like to have them merged
        errors.join(", ")
    else
        # Uncatched Error, comething I don't know, I must return the errors as it is
        errors
    end
    render json: {error: errors_response}, status: status
end
fivehundred!(exception = StandardError.new) click to toggle source
# File lib/concerns/api_exception_management.rb, line 30
def fivehundred! exception = StandardError.new
    return api_error status: 500, errors: exception.message
end
invalid!(exception = StandardError.new) click to toggle source
# File lib/concerns/api_exception_management.rb, line 26
def invalid! exception = StandardError.new
    return api_error status: 422, errors: exception.record.errors 
end
not_found!(exception = StandardError.new) click to toggle source
# File lib/concerns/api_exception_management.rb, line 22
def not_found! exception = StandardError.new
    return api_error status: 404, errors: exception.message
end
unauthenticated!(exception = AuthenticateUser::AccessDenied.new) click to toggle source
# File lib/concerns/api_exception_management.rb, line 13
def unauthenticated! exception = AuthenticateUser::AccessDenied.new
    response.headers['WWW-Authenticate'] = "Token realm=Application"
    return api_error status: 401, errors: exception.message
end
unauthorized!(exception = CanCan::AccessDenied.new) click to toggle source
# File lib/concerns/api_exception_management.rb, line 18
def unauthorized! exception = CanCan::AccessDenied.new
    return api_error status: 403, errors: exception.message
end