Need to return JSON-formatted 404 error in Rails

前端 未结 4 1769
闹比i
闹比i 2020-12-12 11:52

I am having a normal HTML frontend and a JSON API in my Rails App. Now, if someone calls /api/not_existent_method.json it returns the default HTML 404 page. Is

4条回答
  •  天命终不由人
    2020-12-12 12:14

    I like to create a separate API controller that sets the format (json) and api-specific methods:

    class ApiController < ApplicationController
      respond_to :json
    
      rescue_from ActiveRecord::RecordNotFound, with: :not_found
      # Use Mongoid::Errors::DocumentNotFound with mongoid
    
      def not_found
        respond_with '{"error": "not_found"}', status: :not_found
      end
    end
    

    RSpec test:

      it 'should return 404' do
        get "/api/route/specific/to/your/app/", format: :json
        expect(response.status).to eq(404)
      end
    

提交回复
热议问题