Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include Custom exception in Rails?

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...

like image 781
Julien Leray Avatar asked Dec 20 '14 14:12

Julien Leray


People also ask

How do you raise exceptions in Ruby on Rails?

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 ).

How do you handle exceptions in Ruby?

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.


1 Answers

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.

like image 170
fivedigit Avatar answered Oct 10 '22 13:10

fivedigit