2

I am working on a ruby project for the first time. I've got everything I need working except I want to be able to register an unhandled exception handler so I can trigger something if a crash occurs that isn't handled by a rescue but I can't see if that's possible.

I've done with lots of other languages like in Python I've done the following:

sys.excepthook = MyClass._unhandledCrashHandler

I can't find any equivalent to do this in Ruby. Is this possible?

Should have mentioned, I'm writing a Ruby library, so the idea is when the main ruby app initialises my library, the library sets up the handled exception handler and then if the main app crashes, the library gets the crash. This is what I've done in python and many other languages without issue but can't see any way of doing this in Ruby.

Boardy
  • 35,417
  • 104
  • 256
  • 447

1 Answers1

0

Ruby doesn't have generic handlers, but instead you wrap the code which might generate exceptions. For example:

begin
  # ... Do stuff
rescue => e
  $stderr.puts("[%s] %s" % [ e.class, e ])
  $stderr.puts(e.backtrace.join("\n"))
end

Where that rescues all standard exceptions and displays some diagnostic output. You can do whatever you want in the rescue block. Any uncaught exceptions will bubble up to your top-level automatically.

This must be the top-level code for your Ruby application.

The closest thing to what you're talking about in Ruby is the at_exit handler you can define, but this runs in every exit scenario (except terminating the program with exit!) not just uncaught exceptions.

user229044
  • 232,980
  • 40
  • 330
  • 338
tadman
  • 208,517
  • 23
  • 234
  • 262
  • Ah that's annoying, every other language I've worked with allows that. That's not going to work in my case, I knew about the rescue, my library just gets initialised and then not necessarily accessed again (other than may get reinitialised in each class). I'll check that at_exist you mentioned though and see if I can make it work for my use case – Boardy Sep 26 '19 at 21:58
  • 1
    There's no ability to catch all exceptions short of wrapping the main call. I'm not sure why you'd want to rescue everything anyway, in Ruby that's strongly discouraged, so maybe you can better explain the use-case. – tadman Sep 26 '19 at 21:59
  • Its a crash monitoring library. It looks like the at_exit will do what I want to do from a quick test. Thanks for your help – Boardy Sep 26 '19 at 22:06
  • Why not configure something like sentry-raven (https://github.com/getsentry/raven-ruby) to capture application errors? @Boardy – Allison Sep 27 '19 at 05:23
  • 1
    I'm creating my own crash monitoring service :) – Boardy Sep 27 '19 at 10:11
  • The way tools like [Airbrake](https://airbrake.io) do it is by injecting into frameworks that have well-defined ways of capturing errors. In cases without a known framework you need to use the service manually, like `rescue => e; AirBrake.notify(e)` – tadman Sep 27 '19 at 17:11