Quantcast
Channel: Ruby custom error classes: inheritance of the message attribute - Stack Overflow
Viewing all articles
Browse latest Browse all 5

Answer by Huliax for Ruby custom error classes: inheritance of the message attribute

$
0
0

I wanted to do something similar. I wanted to pass an object to #new and have the message set based on some processing of the passed object. The following works.

class FooError < StandardError  attr_accessor :message # this is critical!  def initialize(stuff)    @message = stuff.reverse  endendbegin  raise FooError.new("!dlroW olleH")rescue FooError => e  puts e.message #=> Hello World!end

Note that if you don't declare attr_accessor :message then it will not work. Addressing the OP's issue, you could also pass the message as an additional argument and store anything you like. The crucial part appears to be overriding #message.


Viewing all articles
Browse latest Browse all 5

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>