0

I've got a custom Exception class declared like so:

class CustomError < StandardError
  def initialize(message = nil)
    @message = message
    @type = "custom_error"
  end
end

That is being handled in my Application controller like so:

rescue_from CustomError do |e|
  render json: e.type
end

Now, when I raise the Exception using raise CustomError.new("Oops I did it again") I get a NoMethodError with undefined method `type'

What's going on? Why can't I just access type using e.type?

FloatingRock
  • 6,205
  • 5
  • 39
  • 68

2 Answers2

1

You can't call e.type because you haven't defined a type method.

You can use

attr_reader :type

To add such an accessor.

Frederick Cheung
  • 81,462
  • 7
  • 146
  • 167
0

Turns out I was missing attr_reader. Here's what the final Exception class looks like:

class CustomError < StandardError
  attr_reader :type

  def initialize(message = nil)
    @message = message
    @type = "custom_error"
  end
end

Reference: https://stackoverflow.com/a/4371458/2022751

Community
  • 1
  • 1
FloatingRock
  • 6,205
  • 5
  • 39
  • 68