ciaoben
ciaoben

Reputation: 3338

How can I create a custom exception in my Rails application?

I am trying to create custom exceptions in rails, but I 've problem with my designed solution.

Here what I've done so far:

-Create in the app/ folder a folder named errors/ with a file exceptions.rb in it.

app/errors/exceptions.rb:

module Exceptions
    class AppError < StandardError; end
end

raise Exceptions::AppError.new("User is not authorized")

But when I call the controller's action, here is what I get:

NameError (uninitialized constant Exceptions::AppError

Did you mean? TypeError
              KeyError
              IOError
              EOFError


Did you mean? TypeError
              KeyError
              IOError
              EOFError
):

I think I don't have fully understood how to create new directories and files, and use them.

I've read that everything created in the app dir, is eager loaded, so I can't understand where is the problem.

Upvotes: 4

Views: 4774

Answers (1)

Frederick Cheung
Frederick Cheung

Reputation: 84114

Short version: this is about rails' automated code loading - the fact that in this case the files contain exceptions doesn't matter (see guide on the subject for more details)

Rails would try to load this from exceptions/app_error.rb, in any of the files that are on its auto load path. Because you file naming doesn't match this, it can't find the definition and you get a NameError.

If you don't care about code reloading (and you might not for this sort of content) then you can keep the files as they are but require them in an initialiser (ensure that app/errors is in the load path):

require 'exceptions'

If not then you'll have to rearrange your files to match. If you add app/errors to rails' autoload path and keep the files as is, then it should work. If you don't want to change the autoload path then you'd have to mode it to somewhere in the autoload path and ensure the nesting of modules reflects the organization on disk.

Personally I'd probably stick these in lib and require them with an initialiser

Upvotes: 3

Related Questions