Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Registering handler for unhandled exceptions

Tags:

exception

ruby

Is it possible to define an exception handler for any unhandled exceptions? Wrapping my entire code block in a begin/rescue/end block feels messy.

like image 683
Matty Avatar asked Dec 28 '22 01:12

Matty


1 Answers

How about using at_exit? It should be called even when an exception occurs and you can log the last exception using $!

Here is an example:

at_exit {
puts "Last exception: (#{$!.inspect})"
puts "Backtrace: \n#{$@}"
puts "Exiting..."
}

puts "my app..."
raise "Exception!"

http://www.ruby-doc.org/core-1.9.3/Kernel.html#method-i-at_exit

like image 71
Jesus Castello Avatar answered Jan 15 '23 04:01

Jesus Castello