Catch all exceptions in a rails controller

后端 未结 6 935
春和景丽
春和景丽 2020-11-28 02:20

Is there a way to catch all uncatched exceptions in a rails controller, like this:

def delete
  schedule_id = params[:scheduleId]
  begin
    Schedules.delet         


        
6条回答
  •  有刺的猬
    2020-11-28 03:14

    Actually, if you really want to catch everything, you just create your own exceptions app, which let's you customize the behavior that is usually handled by the PublicExceptions middleware: https://github.com/rails/rails/blob/4-2-stable/actionpack/lib/action_dispatch/middleware/public_exceptions.rb

    • location in stack https://github.com/rails/rails/blob/4-2-stable/railties/lib/rails/application/default_middleware_stack.rb#L98-L99
    • configuring https://github.com/rails/rails/blame/4-2-stable/guides/source/configuring.md#L99
      • which can be as easy as using the routes http://blog.plataformatec.com.br/2012/01/my-five-favorite-hidden-features-in-rails-3-2/ or a custom controller (but see https://github.com/rails/rails/pull/17815 for reasons not to use the routes)

    A bunch of the other answers share gems that do this for you, but there's really no reason you can't just look at them and do it yourself.

    A caveat: make sure you never raise an exception in your exception handler. Otherwise you get an ugly FAILSAFE_RESPONSE https://github.com/rails/rails/blob/4-2-stable/actionpack/lib/action_dispatch/middleware/show_exceptions.rb#L4-L22

    BTW, the behavior in the controller comes from rescuable: https://github.com/rails/rails/blob/4-2-stable/activesupport/lib/active_support/rescuable.rb#L32-L51

提交回复
热议问题