I'm defining a custom Exception on a model in rails as kind of a wrapper Exception: (begin[code]rescue[raise custom exception]end)

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.

This is going on an automated import method of a model that gets populated by POST request to from foreign datasource.

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.

推荐答案

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

Ruby-on-rails相关问答推荐

Gemfile需要较新版本的依赖项

错误AESGCMOpen获取密码:消息身份验证失败:Golang解密GCM

使用带有 Paper Trail gem 的子类

在 POST 请求中添加了 Rails 奇怪的参数

params.permit ruby​​3.2.1 更新后 Active::Record 的未定义方法=~

Rails 7 应用程序 - 引用模型文件时出现未初始化常量错误

只允许用户在 Rails 中输入字母和数字

在 Ruby on Rails html.erb 文件中循环

你如何发布到 Capybara 中的 URL?

在命名空间内设计

如何避免 RSpec 3.0 中 stub_chain 的弃用警告?

OpenSSL::SSL::SSLError: SSL_connect SYSCALL returned=5 errno=0 state=SSLv3 read server hello A

禁用 RVM 或使用没有 RVM 安装的 Ruby?

如何验证 ActiveRecord 中邮箱字段的格式?

如何使用 Ruby 在现有 PDF 上编辑或书写?

Rails 3.0 中的 f.error_messages

登录delay_job?

使用 ruby​​ on rails 活动记录插入多条记录

Sidekiq Rails 4.2 使用 Active Job 还是 Worker?有什么不同

ruby on rails 如何处理 NaN