How to catch all exceptions in ruby?

How to catch all exceptions in ruby?

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.

How to catch all exceptions in ruby?

Leave a Reply

Your email address will not be published.