6

How can we catch or/and handle all unhandled exceptions in ruby?

The motivation for this is maybe logging some kind of exceptions to different files or send and e-mail to the system administration, for example.

In Java we will do

Thread.setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler ex);

In NodeJS

process.on('uncaughtException', function(error) {
   /*code*/
});

In PHP

register_shutdown_function('errorHandler');

function errorHandler() { 
    $error = error_get_last();
    /*code*/    
}

How can we do this with ruby?

GarouDan
  • 3,743
  • 9
  • 49
  • 75

2 Answers2

11

Advanced solution use exception_handler gem

If you want just to catch all exceptions and put for example in your logs, you can add following code to ApplicationController:

begin
  # do something dodgy
rescue ActiveRecord::RecordNotFound
  # handle not found error
rescue ActiveRecord::ActiveRecordError
  # handle other ActiveRecord errors
rescue # StandardError
  # handle most other errors
rescue Exception
  # handle everything else
end

More details you can find in this thread.

Community
  • 1
  • 1
w1t3k
  • 228
  • 2
  • 12
3

In Ruby you would just wrap your program around a begin / rescue / end block. Any unhandled exception will bubble up to that block and be handled there.

Carl Tashian
  • 159
  • 4
  • Is this works even if we have an exception being thrown from another file or by a third party library? – GarouDan Feb 03 '17 at 17:31