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?
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.
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.
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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With