2014-04-02 13:22:10 -04:00
|
|
|
module JsonError
|
|
|
|
|
|
|
|
def create_errors_json(obj)
|
|
|
|
|
|
|
|
# If we're passed a string, assume that is the error message
|
|
|
|
return {errors: [obj]} if obj.is_a?(String)
|
|
|
|
|
2014-08-11 14:42:50 -04:00
|
|
|
# If it's an AR exception target the record
|
|
|
|
obj = obj.record if obj.is_a?(ActiveRecord::RecordInvalid)
|
|
|
|
|
2014-04-02 13:22:10 -04:00
|
|
|
# If it looks like an activerecord object, extract its messages
|
|
|
|
return {errors: obj.errors.full_messages } if obj.respond_to?(:errors) && obj.errors.present?
|
|
|
|
|
2014-09-02 16:22:52 -04:00
|
|
|
# If we're passed an array, it's an array of error messages
|
|
|
|
return {errors: obj.map {|e| e.to_s}} if obj.is_a?(Array) && obj.present?
|
|
|
|
|
|
|
|
# Log a warning (unless obj is nil)
|
|
|
|
Rails.logger.warn("create_errors_json called with unrecognized type: #{obj.inspect}") if obj
|
|
|
|
|
2014-04-02 13:22:10 -04:00
|
|
|
# default to a generic error
|
|
|
|
JsonError.generic_error
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def self.generic_error
|
|
|
|
{errors: [I18n.t('js.generic_error')]}
|
|
|
|
end
|
|
|
|
|
|
|
|
end
|