0

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.

0

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm agree in part with your point, what I'm asking for is conceptually similar to rescue_from class method used in ActionController but in the top level part of a program. It could be very useful and DRY in some cases.
Agreed, there are times it's useful. That's why it's a code smell, not an anti-pattern :)
1

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

1 Comment

I know that, but nice hint. However that won't solve the generic issue.
0

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.