You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby自定义异常类如何获取message?调用返回类名问题

自定义异常的message属性访问问题

当然可以访问自定义异常的message属性,但你的代码里有两个关键问题导致没拿到预期结果:

  1. 你的initialize方法没有接收消息参数,也没有调用父类(StandardError)的构造函数来设置消息
  2. StandardError默认的message实现,如果没有通过super设置过消息,就会返回异常类的全名,这就是你看到那串类名字符串的原因

来修正一下你的代码:

class MyCustomError < StandardError
  attr_reader :object

  def initialize(object, message = "a message")
    super(message) # 必须调用super让父类处理消息存储
    @object = object
    puts message # 现在这里就能输出预期的内容了
  end
end

这里的核心是super(message)——StandardError的构造函数会帮你把消息存起来,这样后续调用异常实例的message方法时,就能返回你传入的内容了。

如果你需要根据传入的object生成动态消息,也可以这么写:

class MyCustomError < StandardError
  attr_reader :object

  def initialize(object)
    @object = object
    # 动态生成消息并传给父类
    super("处理对象 #{object} 时发生错误")
  end
end

# 测试一下
begin
  raise MyCustomError.new("user_123")
rescue MyCustomError => e
  puts e.message # 输出:处理对象 user_123 时发生错误
end

简单来说,只要在自定义异常的初始化方法里,通过super把消息传递给父类的构造函数,就能正常访问message属性啦。

内容的提问来源于stack exchange,提问作者CyberMew

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:04:09