2019-05-03 06:17:27 +08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2014-04-03 01:22:10 +08:00
|
|
|
module JsonError
|
2017-09-06 22:21:07 +08:00
|
|
|
def create_errors_json(obj, opts = nil)
|
|
|
|
opts ||= {}
|
|
|
|
|
2015-02-09 04:25:03 +08:00
|
|
|
errors = create_errors_array obj
|
2017-09-06 22:21:07 +08:00
|
|
|
errors[:error_type] = opts[:type] if opts[:type]
|
|
|
|
errors[:extras] = opts[:extras] if opts[:extras]
|
2015-02-09 04:25:03 +08:00
|
|
|
errors
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def create_errors_array(obj)
|
2014-04-03 01:22:10 +08:00
|
|
|
# If we're passed a string, assume that is the error message
|
2015-03-19 19:22:56 +08:00
|
|
|
return { errors: [obj] } if obj.is_a?(String)
|
2014-04-03 01:22:10 +08:00
|
|
|
|
2014-08-12 02:42:50 +08:00
|
|
|
# If it's an AR exception target the record
|
|
|
|
obj = obj.record if obj.is_a?(ActiveRecord::RecordInvalid)
|
|
|
|
|
2014-04-03 01:22:10 +08:00
|
|
|
# If it looks like an activerecord object, extract its messages
|
2015-03-19 19:22:56 +08:00
|
|
|
return { errors: obj.errors.full_messages } if obj.respond_to?(:errors) && obj.errors.present?
|
2014-04-03 01:22:10 +08:00
|
|
|
|
2014-09-03 04:22:52 +08:00
|
|
|
# If we're passed an array, it's an array of error messages
|
2015-03-19 19:22:56 +08:00
|
|
|
return { errors: obj.map(&:to_s) } if obj.is_a?(Array) && obj.present?
|
2014-09-03 04:22:52 +08:00
|
|
|
|
2018-10-15 09:43:31 +08:00
|
|
|
if obj.is_a?(Exception)
|
|
|
|
message = obj.cause.message.presence || obj.cause.class.name if obj.cause
|
|
|
|
message = obj.message.presence || obj.class.name if message.blank?
|
|
|
|
return { errors: [message] } if message.present?
|
|
|
|
end
|
|
|
|
|
2019-05-22 22:39:08 +08:00
|
|
|
return { errors: [I18n.t("not_found")] } if obj.is_a?(HasErrors) && obj.not_found
|
2019-05-22 20:18:38 +08:00
|
|
|
|
2014-09-03 04:22:52 +08:00
|
|
|
# Log a warning (unless obj is nil)
|
|
|
|
Rails.logger.warn("create_errors_json called with unrecognized type: #{obj.inspect}") if obj
|
|
|
|
|
2014-04-03 01:22:10 +08:00
|
|
|
# default to a generic error
|
|
|
|
JsonError.generic_error
|
|
|
|
end
|
|
|
|
|
2015-02-09 04:25:03 +08:00
|
|
|
def self.generic_error
|
2015-03-19 19:22:56 +08:00
|
|
|
{ errors: [I18n.t("js.generic_error")] }
|
2015-02-09 04:25:03 +08:00
|
|
|
end
|
2014-04-03 01:22:10 +08:00
|
|
|
end
|