简体   繁体   中英

How to catch all exceptions in ruby?

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?

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM