Pregunta

Using rails-api :

  def show
    render json: Room.find(params[:id])
  end

This works when the resource is found. But looking for one that doesn't exist returns a 500 error. Shouldn't this return 404?

> http --json GET chat.dev/api/v1/rooms/23
HTTP/1.1 500 Internal Server Error
Connection: close
Content-Type: text/plain; charset=utf-8
X-Request-Id: 4cd2ba9f-0f85-4530-9c0a-0ef427ac5b31
X-Runtime: 0.094633

ActiveRecord::RecordNotFound at /api/v1/rooms/23
================================================

> Couldn't find Room with id=23

app/controllers/api/v1/rooms_controller.rb, line 20
---------------------------------------------------

``` ruby
   15         #     render :json => {}, :status => :not_found
   16         #   end
   17         # end
   18   
   19         def show
>  20           render json: Room.find(params[:id])
   21         end
   22   
   23       end
   24   
   25     end    
¿Fue útil?

Solución

Just ran into the same thing. In regular Rails, not rails-api. Hope to come up with something better, but so far I just do (as hinted above):

def show
  render json: Room.find(params[:id])
rescue ActiveRecord::RecordNotFound
  render json: {}, status: :not_found
end

I suppose this is reasonable if you think about Rails' "rescue and return 404 only in production" feature as a convenient default, but when you care more about status codes, you need to get your hands (and code) a bit dirty.

Otros consejos

500 internal server error is returned whenever there is an exception on the server. ActiveRecord::RecordNotFound is an exception, so it returns 500.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top