Home > Blockchain >  how to add attributes to custom rails exceptions
how to add attributes to custom rails exceptions

Time:08-03

Say I have a custom error class that inherits from a parent error class. How can I add an attribute to that class, so something like:

class CustomError <CustomParentErrorClass
  status: 500
end 

So that in my controller I could do something like

rescue CustomErroClass => e
 head(e.status)

I essentially want to access my attribute from my rails error class from my controller but am not sure how to. Any thoughts?

CodePudding user response:

You can define attributes on the CustomError class just like any other error class

class CustomError < StandardError
  attr_reader :status

  def initialize(status)
    @status = status
  end
end

Here is a sample usage

begin
  raise CustomError.new(500)
rescue CustomError => e
  head(e.status)
end

If the attributes are hard-coded and do not need to be passed from where the error is raised, you can hard-code it

class CustomError < StandardError
  attr_reader :status

  def initialize
    @status = 500 # you can also define a constant instead of attribute if the value will be a constant
  end
end

That said, a word of caution for the example that you shared:

You are defining a status attribute. I am guessing this error will be raised from your model or service class and rescued in the Controller. If this is the case, consider avoiding coupling the model class to the HTTP status that the controller should return.

  • Related