Skip to content

Instantly share code, notes, and snippets.

@mpouleijn
Created June 4, 2012 07:02
Show Gist options
  • Save mpouleijn/2866841 to your computer and use it in GitHub Desktop.
Save mpouleijn/2866841 to your computer and use it in GitHub Desktop.
5 things you didn't know about exceptions - By Avdi Grimm
# What the heck is $! ?
require 'English'
puts $!.inspect
begin
raise "Oops"
rescue
puts $!.inspect
puts $ERROR_INFO.inspect
end
puts $!.inspect
# nil
# #<RuntimeError: Oops>
# #<RuntimeError: Oops>
# nil
Here is the video
http://www.youtube.com/watch?v=p5BdCR-fcTI&feature=youtu.be#t=17m48s
# case
case obj
when Numeric, String, NilClass, FalseClass, TrueClass
puts "scalar"
# ...
end
# rescue
rescue SystemCallError, IOError, SignalException
# handle exception...
end
# Add a simple crash logger
at_exit do
if $!
open['crash.log', 'a'] do |log|
error = {
:timestamp => Time.now,
:message => $!.message,
:backtrace => $!.backtrace,
:gems => Gem.loaded_specs.inject({}){
|m, (n, s) | m.merge(n => s.version)
}
}
YAML.dump(error, log)
end
end
end
# https://github.com/avdi/zero-zero
# Nested exceptions
class MyError < StandardError
attr_reader :original
def initialize(msg, original=$!)
super(msg);
@original = original
end
end
begin
begin
raise "Error A"
rescue => error
raise MyError, "Error B"
end
rescue => error
puts "rescued: #{error.inspect}"
puts "Original: #{error.original.inspect}"
end
class Net::HTTPResponse
def exception(message="HTTP Error"
RuntimeError.new("#{message}: #{code}")
end
end
#...
responde = Net::HTTP.get_response(url)
raise response
module RaiseExit
def raise(msg_or_exc, msg = msg_or_exc, trace = caller)
warn msg.to_s
exit! 1
end
end
class Object
include RaiseExit
end
# https://github.com/avdi/hammertime
# Retry
tries = 0
begin
tries =+ 1
puts "Trying #{tries}..."
raise "Didn't work"
rescue
retry if tries <
puts "I give up"
end
# Trying 1...
# Trying 2...
# Trying 3...
# I give up
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment