0

I have a custom error class like this:

class EntityCrudError < StandardError
    attr_reader :action
    attr_reader :modelName
    attr_reader :entity
    attr_reader :errors
    def initialize(action, model, entity = nil)
      @action = action
      @model = model
      @entity = entity
      @errors = entity.respond_to?(:errors) ? entity.errors : nil
    end
end

I use this in a Sinatra web application. When the error occurs I send an instance of this object in JSON format:

myError.to_json

this to_json method is the ActiveSupport implementation.

However, the message is not in the JSON object since it's not an instance variable. I need that message in my JSON object. I had two ideas to do this but both of them don't work...

  1. Make the message an instance variable in initialize, but there it doesn't seem to exist yet.
  2. Merge the message into the JSON object, but I don't know how to merge it.

Which of both is the best and how do I implement it?

3
  • what is the attribute that is missing called? myError.message? Commented May 8, 2013 at 8:11
  • @MatthewGraves Yes, but .message is a function that returns it. That's the way Errors work in Ruby.
    – MarioDS
    Commented May 8, 2013 at 8:12
  • Thank you for the ruby lesson. Commented May 8, 2013 at 8:15

1 Answer 1

0

I just thought of something that works:

class EntityCrudError < StandardError
  ..
  ..

  def to_json
    @message = self.message
    super
  end
end

So I just make an instance variable when I need to JSONify the class, and then let the super implementation do the rest.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.