0

In my controller I have this code in one of my actions:

begin
  @user = User.find(params[:id])
  @user.destroy
rescue ActiveRecord::RecordNotFound
  render :json => {"status" => "404", "message" => "User with id #{params[:id]} not found"}
  return
end

And is working fine, but I dont want to copy paste it to all the methods which require to run a Select query.

So I found this answer How to redirect to a 404 in Rails?

And then tried slightly different since I am rendering JSON API endpoints instead templates. Note also I dont know if that params[:id] will be defined there.

  def not_found
    render :json => {"status" => "404", "message" => "User with id #{params[:id]} not found"}
  end

Anyway I modified the query with:

@user = User.find(params[:id]) or not_found

But is still raising the ActiveRecord::RecordNotFound exception.

Also would it be possible to create a generic not_found action which I can use in all the controllers which I can pass it the id parameter and the type of the Object?

Like some generic 404, 500, 400, 200 methods which render JSON responses where I can just pass some parameters

Community
  • 1
  • 1
lapinkoira
  • 8,320
  • 9
  • 51
  • 94

1 Answers1

4

Use rescue_from in your ApplicationController:

class ApplicationController
     rescue_from ActiveRecord::RecordNotFound, with: :show_not_found_errors

     # All the information about the exception is in the parameter: exception
     def show_not_found_errors(exception)
        render json: {error: exception.message}, status: :not_found
     end
end

Thus, any ActiveRecord::RecordNotFound will be rescued with show_not_found_errors method. Add these codes in ApplicationController, and it will works for all the others controllers which is inherited from ApplicationController.

lei liu
  • 2,735
  • 1
  • 16
  • 18
  • Thanks for your response! With your code I am receiving now an empty JSON when the object is not found, should I replace render json: exception, status: :not_found with my code? – lapinkoira Apr 16 '16 at 11:44
  • I see, is there a way I can extend this code to all the controllers of my application? or must I define them in all of them. – lapinkoira Apr 16 '16 at 11:51
  • @lapinkoira just in ApplicationController, check my update. – lei liu Apr 16 '16 at 11:56
  • mm alright, do you think it would be possible to detect which kind of object raised the exception? So it can write down User not found... Collection not found... etc – lapinkoira Apr 16 '16 at 11:58
  • All the informations you need is in the params: exception, it a instance of ActiveRecord::RecordNotFound, try exception.message as my update. – lei liu Apr 16 '16 at 12:22