Julien Leray
Julien Leray

Reputation: 1687

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

Upvotes: 5

Views: 5891

Answers (2)

SHS
SHS

Reputation: 7744

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.

Upvotes: 3

fivedigit
fivedigit

Reputation: 18672

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.

Upvotes: 4

Related Questions