i am creating some custom exceptions as follows
lib/exceptions.rb
module Exceptions
class MemberOverFlow < StandardError
end
rescue_from MemberOverFlow do |exception|
redirect_to root_url, :alert => exception.message
end
end
I use to raise the exception like this.
raise Exception::MemberOverFlow"member count overflow"
It giving the following error
NoMethodError in MembersController#create
undefined method `MemberOverFlow' for Exception:Class
can anyone tell me what is problem
thanks
Ruby actually gives you the power to manually raise exceptions yourself by calling Kernel#raise. This allows you to choose what type of exception to raise and even set your own error message. If you do not specify what type of exception to raise, Ruby will default to RuntimeError (a subclass of StandardError ).
Raising Exceptions in Ruby At its core, every Ruby exception stems from a built-in Exception class, and includes a handful of built-in methods, but the most commonly used exception method is message. This method can be used to retrieve a specific exception message from a raised exception object.
Custom exceptions provide you the flexibility to add attributes and methods that are not part of a standard Java exception. These can store additional information, like an application-specific error code, or provide utility methods that can be used to handle or present the exception to a user.
Did you require the module in the controller where you are trying to raise the exception?
require "exception" #or wherever you have placed the module file
Use:raise Exception::MemberOverFlow.new("member count overflow")
and if it still does not work, try changing the name of the module "Exception" because Exception is an existing exception class defined in Ruby.
No one specifically called out what was wrong in the original post. The following:
raise Exceptions::MemberOverFlow"member count overflow"
is treating MemberOverFlow
as a METHOD and not the class
that it is. You need to call the new
method on your MemberOverFlow
class, which is what amit_saxena's answer points out.
That answer solves the problem, but I just felt it was worth pointing out what you were doing syntactically so that if you ever had a similar problem in the future you would know what was going on.
The contents of your lib directory are not automatically loaded in rails 3, you need to specify them like so in config/application.rb:
config.autoload_paths += %W(#{config.root}/lib)
Perhaps you have not done that?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With