API User : When a record is not found then error message should be clear about what record is not found.
API User : And use status code 404 to indicate that record was not found.
API builder : I am used to writing code like current_user.cars.find
params[:car_id]
. It raises an exception when record is not found.
API User: Yeap. That code needs slight tweaking when it is used inside an API. Rather than raising an excpetion send a clear error message when record is not found.
API builder : This is what I have right now.
1class Api::V1::CarAlertsController < Api::V1::BaseController
2
3 before_action :load_car
4
5 private
6
7 def load_car
8 @car = current_user.cars.find params[:car_id]
9 end
10
11end
API builder : In the above code the issue is that if there is no car matching params[:car_id]
then above code would raise ActiveRecord::RecordNotFound
exception.
1class Api::V1::CarAlertsController < Api::V1::BaseController
2
3 before_action :load_car
4
5 def show
6 if @car
7 ...
8 else
9 message = "No car was found for car_id #{params[:car_id]}."
10 render json: { error: message }, status: :not_found
11 end
12 end
13
14 private
15
16 def load_car
17 @car = current_user.cars.find_by_id params[:car_id]
18 end
19
20end