到目前为止,我有这个......
class MembersController < ApplicationController
rescue_from Mailchimp::Exception::DataException,
Mailchimp::Exception::APIKeyError,
Mailchimp::Exception::NotFound,
Mailchimp::Exception::Duplicate,
Mailchimp::Exception::MissingField,
Mailchimp::Exception::BadRequest,
Mailchimp::Exception::UnknownAttribute,
Mailchimp::Exception::MissingId,
with: :error
def error(e)
puts 'Message: ' + e.message
puts 'Type: ' + e.type
puts 'Title: ' + e.title
e.errors.each do |error|
puts 'Field: ' + error['field']
puts 'Message: ' + error['message']
end if e.errors
# Respond to the HTTP POST request by passing the errors
return render_with(500, e.message, e.errors)
end
private
def render_with(status_code, message, errors='none')
if errors == 'none'
status = 'success'
success = true
else
status = 'error'
success = false
end
render json: {
:status => status,
:success => success,
:message => message,
:errors => errors,
:params => params.as_json
},
status: status_code
end
end
为了让它干涸,我已经做到了......
class MembersController < ApplicationController
mailchimpExceptions = [
'DataException',
'APIKeyError',
'NotFound',
'Duplicate',
'MissingField',
'BadRequest',
'UnknownAttribute',
'MissingId'
]
exceptions = Array.new
mailchimpExceptions.each do |exception|
exceptions << "Mailchimp::Exception::#{exception}"
end
rescue_from *exceptions, with: :error
def error(e)
puts 'Message: ' + e.message
puts 'Type: ' + e.type
puts 'Title: ' + e.title
e.errors.each do |error|
puts 'Field: ' + error['field']
puts 'Message: ' + error['message']
end if e.errors
# Respond to the HTTP POST request by passing the errors
return render_with(500, e.message, e.errors)
end
private
def render_with(status_code, message, errors='none')
if errors == 'none'
status = 'success'
success = true
else
status = 'error'
success = false
end
render json: {
:status => status,
:success => success,
:message => message,
:errors => errors,
:params => params.as_json
},
status: status_code
end
end
我想知道是否所有异常都可以在一个类下进行,因此只有一个类被调用为rescue_from MailchimpExceptions, with: :error
。 This answer by mgolubitsky表明这是可能的,但我不知道如何去做。
我正在使用gem&#39; mailchimp_api_v3&#39;。
答案 0 :(得分:2)
我不知道mailchimp本身,但我一般可以建议如何正确干燥:
EXCEPTIONS = %w|
DataException
APIKeyError
NotFound
Duplicate
MissingField
BadRequest
UnknownAttribute
MissingId|.map { |e| Mailchimp::Exception.const_get(e) }
rescue_from *EXCEPTIONS, with: :error
或rescue_from
所有异常,一次在Mailchimp::Exception
中定义:
EXCEPTIONS = Mailchimp::Exception.constants.map do |e|
Mailchimp::Exception.const_get(e)
end.select { |e| e.is_a?(Class) && e < Exception }
答案 1 :(得分:1)
查看https://github.com/dominicsayers/mailchimp_api_v3#exception-handling
它说:
所有异常都是Mailchimp :: Exception的子类
尝试rescue_from Mailchimp::Exception, with: :error