1

I have a Rails 3 app that is using the exception_notification gem to send emails about exceptions.

I would also like to show users specific error messages when exceptions occur, but by catching a generic Exception because I'm not sure of all the exceptions that can occur. I'm thinking the way to do this is to rescue from Exception, and then raise a custom exception. That way I'm still getting an email about the exception, and the user can see the custom exception's error page.

Does this sound like a Rails 3 way to do things?

Thanks a lot.

mstrom
  • 1,655
  • 3
  • 26
  • 41

1 Answers1

4

I think not.

As Ryan Davis says

Don’t rescue Exception. EVER. Or I will stab you.

More info about that statement here.

Rails 3.2 does exception handling in two middlewares:

  • ActionDispatch::ShowExceptions
  • ActionDispatch::DebugExceptions

You can check that one by running

$ rake middleware 

ActionDispatch::ShowExceptions [source]

Used in production to render the exception pages.

ActionDispatch::DebugExceptions [source]

Used in development environment to render detailed stack traces when exceptions occur. Stops the middleware call chain and renders the stack trace if action_dispatch.show_detailed_exceptions is true to be more precise.


So the most simple way of doing something normal with this middleware would be monkeypatching the call method of ActionDispatch::DebugExceptions, doing all you need to do and then calling the original method.

The better way of doing this is, however, including your own middleware between those two. In it, you would wrap the call inside a rescue block and do your custom processing.

I am a maintainer of Airbrake and this is exactly what we're doing right now.

You might also want to check Errbit, the self-hosted alternative.

Community
  • 1
  • 1
shime
  • 8,746
  • 1
  • 30
  • 51
  • Thanks for the great detailed answer. If I just caught StandardError instead, then raised a custom Exception and handled it in ApplicationController, would that work ok? Thanks! – mstrom Feb 06 '13 at 03:39
  • well, you can always use `rescue_from` in you controllers if you want to do it in your controller. [check this answer](http://stackoverflow.com/questions/3694153/catch-all-exceptions-in-a-rails-controller) – shime Feb 06 '13 at 11:09
  • Thanks again. But if I catch it in the controller and not let it get all the way to the application controller, I don't think the exception_notification gem will know the exception was thrown. – mstrom Feb 06 '13 at 13:57