Rails: stop ActiveRecord::RecordNotFound from breaking app

Posted on Updated on

Was building a rails api backend, but when I would search for a record that was not found, the app would show the error. That is great for testing, but I wanted to handle the error without a 404 since this is an api and wanted to send a specific json message.

Found the solution as such:

class YourController < ActionController::Base

  rescue_from ActiveRecord::RecordNotFound, with: :dude_wheres_my_record

  def show
    # your original code without the begin and rescue
  end

  def dude_where_my_record
    # special handling here
  end
end

Found on stack overflow thanks to noodl

 

 

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s