Ruby | Error: report_on_exception is true - ruby

I'm trying to execute the following program:
Thread.new {
AnsibleReboot::sshRebootRequest(params)
}
Inside of "sshRebootRequest" i have this code:
def self.sshRebootRequest(params)
exc = Executor.new("reboot", params) # Create an object of the class Executor
output = exc.module # Execute the module
data = ParseOutput(output.to_s, params)
sendData(data)
end
I don't know what happen, but when i execute it, i obtain the following error:
terminated with exception (report_on_exception is true):
Anyone know's what happen?, thanks in advance (I'm newbie in Ruby).

Related

Wrong Number of Arguments in Initialize (given 0, expected 1)

I am following along with a tutorial at:
http://neurogami.com/content/neurogami-10_minutes_to_your_first_Ruby_app/#sidebar4
I have checked and rechecked the code, and I do not understand why ruby is not reading my variable app_map as a valid argument.
I have searched online for similar questions, and they exist, yet I can not understand why this variable is not working. I also am not exactly sure what initialize means, as I am an absolute beginner with Ruby. Any insight would be greatly appreciated.
#!/usr/bin/env ruby
class Launcher
def initialize (app_map)
#app_map = app_map
end
#execute the given file using the associate app
def run file_name
application = select_app file_name
system "#{application} #{file_name}"
end
#given a file, lookup the matching application
def select_app file_name
ftype = file_type file_name
#app_map[ ftype ]
end
#return the part of the file name string after the last '.'
def file_type file_name
File.extname( file_name ).gsub( /^\./, '' ).downcase
end
end
launcher = Launcher.new
end
I am not sure what this code is supposed to run, but I have multiple error messages.
tinyapp.rb:8:in `initialize': wrong number of arguments (given 0, expected 1) (ArgumentError)
from tinyapp.rb:30:in `new'
from tinyapp.rb:30:in `<main>'
In this line, you are instantiating a Launcher:
launcher = Launcher.new
That will call the initialize method on it. That method expects an argument:
def initialize (app_map)
#app_map = app_map
end
In order to resolve the error, you will need to pass in a parameter for the app_map argument. I don't know what it's supposed to actually be here, but that'll look something like this:
launcher = Launcher.new(the_app_map)

How to manually create exception with message and backtrace

How can I create an exception with backtrace?
I know we could do something like this to achieve this:
begin
raise StandardError, "message"
rescue StandardError => exception
exception.backtrace
end
Or
exception = StandardError.new("message")
exception.set_backtrace(caller)
But I am looking for something like this:
exception = StandardError.new("message", backtrace: caller)
Is there a way that I can initialize an exception with customized message and backtrace?
You can't initialize an exception with a backtrace, but you can assign one right after initialization.
exception = StandardError.new("message")
exception.set_backtrace(caller)
Wrap in an functional class by yourself:
class ErrorCreator
def self.new(error, message = nil, backtrace: caller)
exception = error.new(message)
exception.set_backtrace(backtrace)
exception
end
end
Use:
ErrorCreator.new(StandardError, "failed")
ErrorCreator.new(StandardError, "failed", backtrace: caller)
I created a gem for anyone to use: https://github.com/JuanitoFatas/active_error.
Along the lines of the other answers, you will need to use set_backtrace on the error object. But you can do this in the initialize method of a custom error like so:
class MyError < StandardError
def initialize(message, backtrace)
super(message)
set_backtrace backtrace
end
end
This way you can encapsulate all your logic in a single class without needing an error factory.
You can create your own exceptions like this :
Create a file in app > exceptions > name_exception.rb
name_exception.rb
class NameException < StandardError
def initialize(message, backtrace)
super
backtrace
end
end
Then in your file
raise NameException.new(message, backtrace)
You can adapt it to your needs but the pattern is here.

Getting undefined error in mass text app

I'm creating a app that sends mass texts using a JSON file with the numbers and names. Every time I test load the app in IRB I get the error:
NameError: undefined local variable or method `data_from_file' for main:Object
from /home/qc/tep/Coding Stuff/Ruby/text app/main.rb:14:in `contacts_from_file'
I understand what the error means, but I don't understand why I'm getting the error, here's the source code:
require 'json'
def sanatize(numbers)
"+1" + number.gsub(/^1|\D/, "")
end
def numbers_from_file
file = open('numbers.json').read
JSON.parse(file)
end
def contacts_from_file
contacts= { }
data_from_file['feed']['entry'].each do |entry|
name = entry['gsx$name']['$t']
number = entry['gsx$number']['$t']
contacts[sanatize(number)] = name
end
contacts
end
def contact_numbers
contacts_from_file.keys
end
def contact_name
contacts_from_file[number]
end
And here's the JSON file:
{
'1**********' => 'Big Bird'
'1**********'} => 'Josh'
}
If anybody could help me and tell me why the data_from_file is "undefined" it would be extremely helpful, thank you ahead of time.
You never define data_from_file, you just try to read from it in the contects_from_file method.
Perhaps you meant numbers_from_file instead of data_from_file?

Collecting exceptions in ruby script

I'm writing a script which collects data from various url's. I want to collect errors from begin rescue blocks into an array to output them when the program runs in verbose mode. With normal use, a failed connection is ignored and the script moves on to the next url.
I thought the best way to do this would be to create an array errArray = Array.new at the top of the script to hold errors, and then do:
rescue Exception => e
errArray << e.message
in various functions to log errors. The die function outputs the array using p unless it is empty. However, I get the error
Undefined local variable or method 'errArray'
Any help (and constructive criticism) appreciated.
EDIT: die function:
def die(e)
p errorArray unless errorArray.empty?
# Some other irrelevant code
end
errArray is not global variable and therefore methods have no access to it. You can declare it as a global variable by $err_array.
However the best solution would be create a simple class:
class ExceptionCollector
def collect
yield
rescue => e
errors << e.message
end
def errors
#errors ||= []
end
end
And then simple:
$logger = ExceptionCollector.new
$logger.collect do
# this may raise an exception
end
def foo
$logger.collect do
# another exception
end
end
$logger.errors #=> list of errors

to_sql not working on update_attributes or .save

I'm looking for a way to store the sql string that is generated in an update or create action. I've tried appending .to_sql to the end of update_attributes but it returns a TrueClass error (or something like that). Is there something that I am missing?
In brief - you need to override ActiveRecord execute method. There you
can add any logic for logging.
connection = ActiveRecord::Base.connection
class << connection
alias :original_exec :execute
def execute(sql, *name)
# try to log sql command but ignore any errors that occur in this block
# we log before executing, in case the execution raises an error
begin
file = File.open(RAILS_ROOT + "/log/sql.txt",'a'){|f| f.puts Time.now.to_s+": "+sql}
rescue Exception => e
;
end
# execute original statement
original_exec(sql, *name)
end
end
credits:
https://stackoverflow.com/a/1629474/643500
https://stackoverflow.com/a/1640560/643500
These methods both return a boolean. You can't invoke to_sql on a boolean.

Resources