How to enable custom exception in Rails?

I don’t understand how Rails includes (or not?) Some file from the application directory.

For example, I created a new application / directory exception to create my own exceptions. Now, from the helpers file, I want to raise one of my exceptions.

Can I include something in this helper?

Assistant: assistants / communication _helper.rb

//should I include something or it suppose to be autoloaded? module CommunicationsHelper begin. . . . raise ParamsException, "My exception is lauch!" rescue StandardError => e ... end end 

Exception: exceptions / params_exception.rb

 class ParamsException < StandardError def initialize(object, operation) puts "Dans paramsException" end end 

Nothing concrete from my rise in output ...

Thanks!

EDIT: Thanks to everyone, your answers were useful in many ways. I did not explain the exception very well, as you said, but I also refuse to update my config.rb. so now i:

 rescue StandardError => e raise ParamsError.new("truc", "truc") 

Another question, do you know where I can catch a raise? Because I'm already in the catch block, so I lost a little ...

+5
source share
2 answers

First of all, I think you are making your exception incorrectly.

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

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

Read this .

Finally, do not save from StandardError if CustomError is a child of StandardError; otherwise, your raise allowance will be saved.

+3
source

If you do not see the output from raise , make sure that you did not save 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 

Ruby usually uses your custom errors with Error rather than Exception as the main note. Unlike some other programming languages, classes ending in Exception are designed for system-level errors.

+4
source

Source: https://habr.com/ru/post/1209608/


All Articles