Fabio
Fabio

Reputation: 19216

How to setup a generic error/exception handler callback in Ruby?

I’m working on this issue: Rails exception notifier in rake tasks

My question: Is there any function/plugin/gem/whatever to setup a generic error/exception handler callback as in PHP with set_error_handler and set_exception_handler?

I need a way to register a callback function used as a catchall outside any begin .. rescue .. end block. For example:

def my_handler *args
  # exception processing code here
end

some_magic_method my_handler

raise "An Exception" # this will be handled by my_handler

In PHP this could be achieved with the set_exception_handler function. Is there any such function in Ruby/Rails?

If such feature exists I could solve my previous issue in a simple way.

A Rails-only solution would be fine for my needs.

Upvotes: 0

Views: 980

Answers (3)

Fabio
Fabio

Reputation: 19216

I found a partial solution to my issue which works for the simple case I mentioned in the question. However this can not catch the exception, but it can be useful if someone needs only exception logging or reporting.

#!/usr/bin/env ruby

at_exit do
  if $!
    puts "Program ended with an exception #{$!.message}"
    puts $!.backtrace.join("\n")
    # or log the exception here
  end
end

loop do
  value = rand(3)
  puts "Value is #{value}"
  break if value == 2 
  raise "An Exception" if value == 0
end

puts "Program ended normally"

Upvotes: 0

Emily
Emily

Reputation: 18203

I don't believe Ruby provides a way to do this, either with exceptions or with throw/catch. In general, doing something this way is a code smell and something to avoid. It makes control flow extremely hard to figure out. I would try to find some other way to approach the problem if at all possible.

Upvotes: 2

Pedro Rolo
Pedro Rolo

Reputation: 29990

If you want to do this in the HTTP Request-handling cycle you may use an around filter in your application controller:

class ApplicationController < ActionController::Base
  around_filter do |controller, action|
    action.call
  rescue ExceptionXPTO
     # ... handle the exception ...
  end
end

Upvotes: 1

Related Questions