5

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

Julien Leray
  • 1,647
  • 2
  • 18
  • 34
  • I would suggest to create a separate controller, and route errors to it. It would look simple. – Nithin Dec 20 '14 at 14:29

2 Answers2

4

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.

fivedigit
  • 18,464
  • 6
  • 54
  • 58
  • 1
    Rails should auto-load everything from `app` subdirectories – Sergio Tulentsev Dec 20 '14 at 14:58
  • I heard about that also, so you think I don't have to add the line config.autoload_paths += %W(#{config.root}/app/exceptions) ? – Julien Leray Dec 22 '14 at 14:46
  • 1
    @JulienLeray I've also tested that just to verify. You indeed don't have to add subdirectories of `app` to the autoload path. If loading failed, you would definitely have seen a `LoadError`, since that one isn't rescued in your code. – fivedigit Dec 22 '14 at 15:19
3

First, I think that you're raising your exception incorrectly.

In your custom exception class, your initialize method takes in arguments. Therefore you should raise it with:

raise CustomError.new(arg1, arg2, etc.)

Read this.

Lastly, don't rescue from StandardError if CustomError is a child of StandardError; otherwise your manual 'raise' will be rescued.

Community
  • 1
  • 1
SHS
  • 7,651
  • 3
  • 18
  • 28