从自定义异常类获取“消息” [英] Getting 'message' from a custom exception class

查看:176
本文介绍了从自定义异常类获取“消息”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题是指此处的答案。我需要访问自定义异常的消息

This question refers to an answer here. I need to access message of a custom exception. Is this possible?

我认为直接调用消息就足够了,如下面的示例:

I thought that directly calling message will suffice as in this example:

class MyCustomError < StandardError
  attr_reader :object

  def initialize(object)
    @object = object
    puts message
  end
end

但这不是我期望的。它给了我一些字符串,例如:

but this is not what I expected it to be. It gave me some string like:

"MyModuleNameHere::MyCustomExceptionClassNameHere"

而不是:

"a message"

我的直觉倾向于否定,因为 initialize 构造函数不会接受消息 文本。

My intuition is leaning towards no, since the initialize constructor does not take the "a message" text.

推荐答案

通过消息并调用 super 通常会接收一条消息,例如 StandardError.new( oh no)

You can pass the message and call super which will normally take a message, e.g. StandardError.new("oh no").

class MyCustomError < StandardError

  def initialize(message, object)
    # ...
    super(message)
  end
end

MyCustomError.new("Oh no", thing).message # => "Oh no"

这本有关Ruby异常的电子书非常值得: http://exceptionalruby.com/

This ebook on Ruby exceptions is well worth it: http://exceptionalruby.com/

这篇关于从自定义异常类获取“消息”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆