Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Catch all exceptions in a rails controller

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

def delete   schedule_id = params[:scheduleId]   begin     Schedules.delete(schedule_id)   rescue ActiveRecord::RecordNotFound     render :json => "record not found"   rescue ActiveRecord::CatchAll     #Only comes in here if nothing else catches the error   end   render :json => "ok" end

Thank you

like image 855
Neigaard Avatar asked Sep 12 '10 08:09

Neigaard


People also ask

How do you handle exceptions in Rails?

Exception handling in Ruby on Rails is similar to exception handling in Ruby. Which means, we enclose the code that could raise an exception in a begin/end block and use rescue clauses to tell Ruby the types of exceptions we want to handle.

What is rescue in Ruby?

A raised exception can be rescued to prevent it from crashing your application once it reaches the top of the call stack. In Ruby, we use the rescue keyword for that. When rescuing an exception in Ruby, you can specify a specific error class that should be rescued from. begin raise 'This exception will be rescued!'

What is exception in Ruby?

In Ruby, exception handling is a process which describes a way to handle the error raised in a program. Here, error means an unwanted or unexpected event, which occurs during the execution of a program, i.e. at run time, that disrupts the normal flow of the program's instructions.


2 Answers

You can also define a rescue_from method.

class ApplicationController < ActionController::Base   rescue_from ActionController::RoutingError, :with => :error_render_method    def error_render_method     respond_to do |type|       type.xml { render :template => "errors/error_404", :status => 404 }       type.all  { render :nothing => true, :status => 404 }     end     true   end end 

Depending on what your goal is, you may also want to consider NOT handling exceptions on a per-controller basis. Instead, use something like the exception_handler gem to manage responses to exceptions consistently. As a bonus, this approach will also handle exceptions that occur at the middleware layer, like request parsing or database connection errors that your application does not see. The exception_notifier gem might also be of interest.

like image 106
BOFH Avatar answered Oct 07 '22 10:10

BOFH


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   raise end 
like image 24
Chris Johnsen Avatar answered Oct 07 '22 11:10

Chris Johnsen