0
votes

First of all, I need to use try-catch (begin-rescue) construction for catching specific errors in controllers for each method. Am I right that try-catch is begin-rescue construction in rails?

What best practice is to create a custom exception, including explicitly the control of values null?

What is the approach for saving all the exceptions in a log file?

For example, I use this code to catch the standard error, when this function receives nothing as a parameter.

  1. How to create a custom exception for this case? when game_number is nill
  2. How to write these errors to an independent log file, using a specific library for log management (log4xxx, logging-rails, logging)?
def fizz_buzz(game_number)
    # list of the numbers, starting from @game.number
    begin
      serie_num = (game_number..Constants::LAST_NUMBER_FIZZBUZZ).to_a
    rescue StandardError => e
      print e
      # how to save this error to independent file using logging lib?
      # how using custom exception for catch errors like this - 
      # game_number = nill?
    end

    new_num = serie_num.map do |num|
      if num % 3 == 0 and num % 5 == 0
        num = 'fizzbuzz'
      elsif num % 3 == 0
        num = 'fizz'
      elsif num % 5 == 0
        num = 'buzz'
      elsif num % 3 != 0 and num % 5 != 0
        num = num
      end
    end

    return new_num.join(', ')
  end

Is it correct to use begin-rescue construction this way?

I use following code-statement in config\enviroments\development.rb for creating new logger to write to the independent file but get just an almost empty file.

config.Logger = Logger.new(ENV["PWD"] + '/fizzbuzz_log.log')

Got in fizzbuzz_log.log just this:

# Logfile created on 2019-06-03 11:47:36 +0200 by logger.rb/56438

Thank you in advance.

1

1 Answers

0
votes
class YourCustomError < StandardError
 attr_accessor :message

 def initialize(message)
    @message = message
 end

  def to_s
    "[#{message}] #{super}"
  end
end

That's how to create your own Error class. And then

 begin
   serie_num = (game_number..Constants::LAST_NUMBER_FIZZBUZZ).to_a
 rescue YourCustomError => e
  #Use logging lib to log or do custom error handling
end

And in your custom method whenever you regard as the error, do this.

raise YourCustomError.new("Error Occured. Contact the System Admin") # the message can be anything specific to your business domain's problem.