I want to know to what exception name I should refer to. I am getting invalid date. I checked the docs and I couldn't find it.
Begin
Date.new(day,month,year)
Rescue exceptionname
statements
I think you're looking for ArgumentError. Using irb:
> Date.new(2,-200, 3)
ArgumentError: invalid date
from (irb):11:in `new'
from (irb):11
so
begin
Date.new(2,-200, 3)
rescue ArgumentError
#your logic
end
Related
I'm using eval on large blocks of code with this rescue block:
rescue => e
logger.error e.message
e.backtrace.each { |line| logger.error line }
end
The rescue block does not provide line number, etc. for the exception. I just get this:
undefined method `+' for nil:NilClass
which is not very helpful when there is a lot of code to evaluate. I tried various things such as:
eval(exp, binding, __FILE__, __LINE__)
but they do not provide any additional information on the line number of where the error is.
May be this can help. This answer is sort of based on details from this article. Assuming that you have expression to be evaluated in exp variable, I adjust the line number value passed as 3rd parameter to String#module_eval.
begin
exp = <<EOL
a = nil
a + 10
EOL
String.module_eval(exp,__FILE__, __LINE__ - 1 - exp.split("\n").size )
rescue Exception => e
puts e
puts e.backtrace
end
The output of above program:
undefined method `+' for nil:NilClass
E:/hello.rb:4:in `<main>'
E:/hello.rb:6:in `module_eval'
E:/hello.rb:6:in `<main>'
[Finished in 0.2s]
I have found myself in need to execute a string. Current method is to use the Kernel#eval() method. Everything is working fine, but my error handling isn't working. For example, a missing closing quotation mark will completely kill and exit the program.
Here's an excerpt. Any idea why I can't catch the error?
def process(str)
print "\n"
eval(str)
rescue => e
puts e
end
>> process('"')
console.rb:90:in `eval': (eval):1: unterminated string meets end of file (SyntaxError)
from console.rb:90:in `process'
from console.rb:81:in `bouncer'
from console.rb:14:in `block in prompt'
from console.rb:11:in `loop'
from console.rb:11:in `prompt'
from console.rb:97:in `<main>'
According to the documentation:
A rescue clause without an explicit Exception class will rescue all StandardErrors (and only those).
SyntaxError is not a StandardError. To catch it, you have to be explicit, e.g.:
def process(str)
print "\n"
eval(str)
rescue Exception => e
puts e
end
process('"')
Output:
(eval):1: unterminated string meets end of file
I have this simple fairly code under the following
$: << File.expand_path(File.dirname(__FILE__) + "/../../config")
$: << File.expand_path(File.dirname(__FILE__) + "/../../lib")
require 'activerecord-sqlserver-adapter'
require 'sa.gw.library'
require 'sa.gw.lib.connection_manager'
#connecting to sqlserver test
#app_config = YAML.load_file("#{File.dirname(__FILE__)}/../../config/sa.gw.c.victim.yml")
connection_manager = ConnectionManager.new(#app_config["tpaldb"]) #H
begin
sql = "exec spTPal_Vic_GetDeviceStateByIMEI '000000000000000'"
result = connection_manager.execute_sproc(sql)
result.each {|r|
puts 'hello'
}
connection_manager.connection.close()
rescue => e
puts "An error occurred detail: #{e.message}"
end
I am executing this routine using Aptana Studio 3. What I've experienced is this that the function terminates silently if Stored Procedure doesn't exists without letting user know.
what I want to have a mechanism is to know the procedure doesn't exist in the form message or exception.
stack trace is under the following
["c:/Ruby193/lib/ruby/gems/1.9.1/gems/activerecord-sqlserver-adapter-3.2.12/lib/active_record/connection_adapters/sqlserver/database_statements.rb:416:in `each'", "c:/Ruby193/lib/ruby/gems/1.9.1/gems/activerecord-sqlserver-adapter-3.2.12/lib/active_record/connection_adapters/sqlserver/database_statements.rb:416:in `handle_to_names_and_values_dblib'", "c:/Ruby193/lib/ruby/gems/1.9.1/gems/activerecord-sqlserver-adapter-3.2.12/lib/active_record/connection_adapters/sqlserver/database_statements.rb:405:in `handle_to_names_and_values'", "c:/Ruby193/lib/ruby/gems/1.9.1/gems/activerecord-sqlserver-adapter-3.2.12/lib/active_record/connection_adapters/sqlserver/database_statements.rb:377:in `_raw_select'", "c:/Ruby193/lib/ruby/gems/1.9.1/gems/activerecord-sqlserver-adapter-3.2.12/lib/active_record/connection_adapters/sqlserver/database_statements.rb:371:in `block in raw_select'", "c:/Ruby193/lib/ruby/gems/1.9.1/gems/activerecord-3.2.12/lib/active_record/connection_adapters/abstract_adapter.rb:280:in `block in log'", "c:/Ruby193/lib/ruby/gems/1.9.1/gems/activesupport-3.2.12/lib/active_support/notifications/instrumenter.rb:20:in `instrument'", "c:/Ruby193/lib/ruby/gems/1.9.1/gems/activerecord-3.2.12/lib/active_record/connection_adapters/abstract_adapter.rb:275:in `log'", "c:/Ruby193/lib/ruby/gems/1.9.1/gems/activerecord-sqlserver-adapter-3.2.12/lib/active_record/connection_adapters/sqlserver/database_statements.rb:371:in `raw_select'", "c:/Ruby193/lib/ruby/gems/1.9.1/gems/activerecord-sqlserver-adapter-3.2.12/lib/active_record/connection_adapters/sqlserver/database_statements.rb:354:in `do_exec_query'", "c:/Ruby193/lib/ruby/gems/1.9.1/gems/activerecord-sqlserver-adapter-3.2.12/lib/active_record/connection_adapters/sqlserver/database_statements.rb:24:in `exec_query'", "c:/Ruby193/lib/ruby/gems/1.9.1/gems/activerecord-sqlserver-adapter-3.2.12/lib/active_record/connection_adapters/sqlserver/database_statements.rb:297:in `select'", "c:/Ruby193/lib/ruby/gems/1.9.1/gems/activerecord-3.2.12/lib/active_record/connection_adapters/abstract/database_statements.rb:18:in `select_all'", "c:/Ruby193/lib/ruby/gems/1.9.1/gems/activerecord-3.2.12/lib/active_record/connection_adapters/abstract/query_cache.rb:63:in `select_all'", "J:/SecureAlert_SVN/2.0.5 (Chilli)/lib/sa.gw.lib.connection_manager.rb:27:in `execute_sproc'", "J:/SecureAlert_SVN/2.0.5 (Chilli)/app/controllers/publisher_test.rb:16:in `<main>'"]
In Ruby, the default rescued exception is going to be StandardError. What you have shown here doesn't show what error was raised, or perhaps it was raised from SQL rather than from Ruby.
You are rescuing StandardError then, as you don't specify the exception you are trying to rescue, and it may indeed be the wrong one.
class TwitterProfile < ActiveRecord::Base
def send_status_update(status_update)
if publish?
client = Twitter::Client.new( :oauth_token => authentication.token,
:oauth_token_secret => authentication.secret)
client.update(status_update.to_twitter_string)
end
rescue Exception => e
logger.info "Error publishing to twitter: #{e.to_s}"
end
end
There is a StatusUpdate model and an observer that reposts them to Twitter in after_create. I sometimes get the following exception:
NameError (undefined local variable or method `e' for #<TwitterProfile:0x00000004e44ab8>):
app/models/twitter_profile.rb:23:in `rescue in send_status_update'
app/models/twitter_profile.rb:18:in `send_status_update'
app/models/status_update_observer.rb:6:in `block in after_create'
app/models/status_update_observer.rb:4:in `after_create'
app/models/workout_observer.rb:5:in `after_update'
app/controllers/frames_controller.rb:76:in `update'
app/controllers/application_controller.rb:24:in `call'
app/controllers/application_controller.rb:24:in `block (2 levels) in <class:ApplicationController>'
app/controllers/application_controller.rb:10:in `block in <class:ApplicationController>'
What am I missing here?
I have one thing I know and one that's just a wild guess.
The thing I know is that you don't need to call to_s on an overall #{} expression; that will happen automatically. But it does no harm.
My wild guess is that your test case is not really running the code you have posted. What happens if you change e to f?
I should note that rescuing Exception itself is usually a bad idea. You should rescue RuntimeError or StandardError at the highest, and preferably something more specific. You can get fairly strange errors when rescuing Exception because you interfere with threads and interpreter-level events.
You're missing the 'begin' block of the begin/rescue clause.
I want to write a scope that requires that the start date of products be less than today. I wrote the following in rspec
it "Should not be found with a start date in the future" do
#product.start_date = Date.tomorrow
#product.save
Product.active.find(#product.id).should == nil
end
That test fails, obviously. Then I wrote the scope-
scope :active, where('start_date <= ?', Date.today)
Then I rerun the spec and it fails with-
2) Product Should not be found with a start date in the future
Failure/Error: Product.active.find(#product.id).should_not == true
Couldn't find Product with ID=1 [WHERE (start_date <= '2010-12-20')]
# ./spec/models/product_spec.rb:168:in `block (2 levels) in <top (required)>'
I cannot figure out how to get this code to pass. I do not want the product to be found.
Look at the error: "Couldn't find Product with ID=1", the scope is actually working. Problem is in your test, find raises an exception as usual because no record has been found. You either have to use find_by_id or assert the exception with rspec.