I don't understand well how Rails include (or not?) some file from the app directory.
For example, I've created a new directory app/exceptions for create my own exceptions. Now, from a helpers file, I want to raise one of my exception.
Am I suppose to include something in this helper?
The Helper: helpers/communications_helper.rb
//should I include something or it's suppose to be autoloaded?
module CommunicationsHelper
begin.
.
.
.
raise ParamsException, "My exception is lauch!"
rescue StandardError => e
...
end
end
The exception: exceptions/params_exception.rb
class ParamsException < StandardError
def initialize(object, operation)
puts "Dans paramsException"
end
end
Nothing specific from my raise in the output...
Thanks!
EDIT: Thanks to all, your two answers was helpful in different way. I didn't raise well the exception like you said, but I've also forggot to update my config.rb. so now I 've:
rescue StandardError => e
raise ParamsError.new("truc", "truc")
Other question, do you know where can I catch the raise? Cause I'm already in a catch block, so I'm little lost...
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 ).
Ruby also provides a separate class for an exception that is known as an Exception class which contains different types of methods. The code in which an exception is raised, is enclosed between the begin/end block, so you can use a rescue clause to handle this type of exception.
If you don't see output from your raise
, make sure you're not rescuing the error by accident, since your error is a subclass of StandardError
:
begin
raise ParamsException, "My exception is lauch!"
rescue StandardError => e # This also rescues ParamsException
end
As a side note, in Ruby it's common practice to have your custom errors end with Error
rather than Exception
. Unlike some other programming languages, classes ending with Exception
are meant for system level errors.
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