8

I am new to Ruby. I am writing a Restful API application using Rails 4. How can I return a 404 JSON not found string when the record is not found?

I found a number of posts but no luck, only for Rails 3.

In my controller I can caught the exception

  def show
    country = Country.find(params[:id])
    render :json => country.to_record
  rescue Exception
    render :json => "404"
  end

But I want a generic one to capture all the not found resources.

Darshan Rivka Whittle
  • 32,989
  • 7
  • 91
  • 109
TheOneTeam
  • 25,806
  • 45
  • 116
  • 158

2 Answers2

24

Use rescue_from. See http://guides.rubyonrails.org/v2.3.11/action_controller_overview.html#rescue

In this instance use something like:

class ApplicationController < ActionController::Base
  rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found

  private
  def record_not_found(error)
    render json: { error: error.message }, status: :not_found
  end
end
holodigm
  • 593
  • 6
  • 10
-1

Do:

def show
  country = Country.find(params[:id])
  render :json => country.to_record
rescue Exception
  render :json => 404_json_text, :status => 404
end
SreekanthGS
  • 988
  • 5
  • 12