【发布时间】:2017-08-06 01:26:15
【问题描述】:
到目前为止,我有这个......
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 'mailchimp_api_v3'。
【问题讨论】:
-
你用的是什么宝石?
-
@thaleshcv 'mailchimp_api_v3'
-
是的,这确实是 mailchimp 的疏忽。我认为没有可能的理由 not 为您的 gem 提供一个常见的错误类。也许,你最好的选择是按照@mudasobwa 的建议去做。
-
也许有是的原因,我不知道。请注意,其中大多数 继承自DataException。这样你就可以解救那个和少数几个盗贼了。
-
现在,
RuntimeError是系统类之一,过于通用。不要救那个一个。
标签: ruby-on-rails ruby ruby-on-rails-5