PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 4, 2022

[FIXED] how to add attributes to custom rails exceptions

 August 04, 2022     backend, error-handling, exception, ruby, ruby-on-rails     No comments   

Issue

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?


Solution

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.



Answered By - Ankit
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing