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
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.
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!'
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With