Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 809
GarouDan Avatar asked Feb 03 '17 17:02

GarouDan


People also ask

How to handle exceptions in Ruby?

This can be done automatically by Ruby or manually. Catch and Throw is similar raise and rescue keywords, Exceptions can also be handled using catch and throw keywords in Ruby. Throw keyword generates an exception and whenever it is met, the program control goes to the catch statement.

What happens if no rescue clause matches in Ruby?

If no rescue clause match, or if an exception occurs outside the begin/end block, then Ruby moves up to the stack and looks for an exception handler in the caller. retry Statement: This statement is used to execute the rescue block again from the beginning after capturing the exception.

How to use try catch and raise rescue in Ruby?

In Ruby we have a way to deal with these cases, we have begin, end (default try catch) and we can use try and catch, both try catch and raise rescue used for the same purpose, one will throw exception (throw or raise) with any specific name inside another (catch or rescue). Syntax of try catch in Ruby

What is the use of throw and catch in Ruby?

Catch and Throw is similar raise and rescue keywords, Exceptions can also be handled using catch and throw keywords in Ruby. Throw keyword generates an exception and whenever it is met, the program control goes to the catch statement. The catch block is used to jump out from the nested block and the block is labeled with a name.


2 Answers

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.

like image 149
w1t3k Avatar answered Oct 04 '22 06:10

w1t3k


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.

like image 29
Carl Tashian Avatar answered Oct 04 '22 06:10

Carl Tashian