用参数提升自定义异常 [英] Raise custom Exception with arguments
问题描述
我在rails的一个模型中定义了一个自定义异常作为一个包装器Exception:( begin [code] rescue [raise custom exception] end
)
I'm defining a custom Exception on a model in rails as kind of a wrapper Exception: (begin[code]rescue[raise custom exception]end
)
当我提出异常时,我想传递一些关于a)内部函数引发错误的模型的实例,以及b)抓住了。
When I raise the Exception, I'd like to pass it some info about a) the instance of the model whose internal functions raise the error, and b) the error that was caught.
这是一个自动导入的模式,由外部数据源填充POST请求。
This is going on an automated import method of a model that gets populated by POST request to from foreign datasource.
tldr;鉴于您自己定义了异常,怎么能将参数传递给异常?我有一个该例外的初始化方法,但是 raise
语法似乎只接受一个Exception类和消息,没有可选的参数被传入实例化过程。
tldr; How can one pass arguments to an Exception, given that you define the Exception yourself? I have an initialize method on that Exception but the raise
syntax seems to only accept an Exception class and message, no optional parameters that get passed into the instantiation process.
推荐答案
使用new创建一个异常的实例:
create an instance of your exception with new:
class CustomException < StandardError
def initialize(data)
@data = data
end
end
# => nil
raise CustomException.new(bla: "blupp")
# CustomException: CustomException
这篇关于用参数提升自定义异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!