Commit 949ae68a8c294e63bac1c334cc967fd303b7cb16
1 parent
f719e97e
Exists in
master
and in
1 other branch
Adding file not found handling
If there is no problem for the requested id the api will now correctly return a 404 status.
Showing
3 changed files
with
12 additions
and
4 deletions
Show diff stats
app/controllers/api/v1/problems_controller.rb
| ... | ... | @@ -4,11 +4,15 @@ class Api::V1::ProblemsController < ApplicationController |
| 4 | 4 | |
| 5 | 5 | def show |
| 6 | 6 | result = benchmark("[api/v1/problems_controller/show] query time") do |
| 7 | - problem = Problem.only(FIELDS).find(params[:id]) | |
| 8 | - problem.as_json(include: {errs: { include: :notices}}) | |
| 7 | + begin | |
| 8 | + problem = Problem.only(FIELDS).find(params[:id]) | |
| 9 | + problem.as_json(include: {errs: { include: :notices}}) | |
| 10 | + rescue Mongoid::Errors::DocumentNotFound | |
| 11 | + head :not_found | |
| 12 | + return false | |
| 13 | + end | |
| 9 | 14 | end |
| 10 | 15 | |
| 11 | - | |
| 12 | 16 | respond_to do |format| |
| 13 | 17 | format.any(:html, :json) { render :json => result } # render JSON if no extension specified on path |
| 14 | 18 | format.xml { render :xml => result } | ... | ... |
app/models/problem.rb
spec/controllers/api/v1/problems_controller_spec.rb
| ... | ... | @@ -24,6 +24,11 @@ describe Api::V1::ProblemsController do |
| 24 | 24 | get :show, :auth_token => @user.authentication_token, :format => "json", :id => requested_problem.id |
| 25 | 25 | expect( response.body ).to eq(requested_problem.to_json(include: {errs: { include: :notices}})) |
| 26 | 26 | end |
| 27 | + | |
| 28 | + it "returns a 404 if the problem cannot be found" do | |
| 29 | + get :show, :auth_token => @user.authentication_token, :format => "json", :id => 'IdontExist' | |
| 30 | + expect( response.status ).to eq(404) | |
| 31 | + end | |
| 27 | 32 | end |
| 28 | 33 | |
| 29 | 34 | describe "GET /api/v1/problems" do | ... | ... |