Custom Error Handling with Rails 4.0

后端 未结 5 744
我寻月下人不归
我寻月下人不归 2020-12-24 14:49

I\'m building a Ruby on Rails api using Ruby 2.0 and Rails 4.0. My app is almost solely a JSON API, so if an error occurs (500, 404), I want to capture that error and return

5条回答
  •  清歌不尽
    2020-12-24 15:25

    After trying a few variations I've settle on this as the simplest way to handle the API 404s:

    # Passing request spec
    describe 'making a request to an unrecognised path' do
      before { host! 'api.example.com' }
        it 'returns 404' do
        get '/nowhere'
        expect(response.status).to eq(404)
      end
    end
    
    # routing
    constraints subdomain: 'api' do
      namespace :api, path: '', defaults: { format: 'json' } do
        scope module: :v1, constraints: ApiConstraints.new(1) do
          # ... actual routes omitted ...
        end
        match "*path", to: -> (env) { [404, {}, ['{"error": "not_found"}']] }, via: :all
      end
    end
    

提交回复
热议问题