我想实现基于状态代码引发错误的方法。我试图实现这个代码:
def parse_response
system_errors = { }
(100..199).each do |current|
system_errors[current.to_s] = SystemError
end
(200..999).each do |current|
system_errors[current.to_s] = CommunicationError
end
return params_for_success if successful_response?
# pp system_errors
pp payment_response
if valid?
raise system_errors[340].new(technical_message, response_code)
else
raise errors.full_messages.join(";\n")
end
end
def successful_response?
response_code == RESPONSE_CODE_FOR_SUCCESS
end
def params_for_success
payment_response.dig(:payment_response)
end
.....
class CommunicationError < StandardError
def initialize(current_technical_message, response_code)
@response = response
end
end
但是我得到nil的错误parse_response': undefined method
new':NilClass(NoMethodError)`
根据一系列数字提出错误的正确方法是什么?
此行导致问题:system_errors[:error_class].new(technical_message, response_code)
答案 0 :(得分:0)
与Javascript不同,Ruby不会在类型之间隐式转换。
(200..999).each do |current|
system_errors[current.to_s] = CommunicationError
end
# now we have
system_errors["340"] == CommunicationError
稍后当你做
时raise system_errors[340].new(technical_message, response_code)
它使用 interger 键340
而不是字符串键"340"
。缺少密钥会返回nil
,因此您正在调用nil.new
。决定是否要使用整数或字符串键并在插入/读取时坚持使用它。