2

使用rails-api:

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

これは、リソースが見つかったときに機能します。しかし、存在しないものを探すと 500 エラーが返されます。これは 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    
4

2 に答える 2

5

ちょうど同じことに遭遇しました。rails-api ではなく、通常の Rails で。より良いものを考え出すことを望んでいますが、これまでのところ、私はそうしています(上記で示唆したように):

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

Rails の "rescue and return 404 only in production" 機能を便利なデフォルトとして考えれば、これは合理的であると思いますが、ステータス コードにもっと関心がある場合は、手 (およびコード) を少し汚す必要があります。

于 2013-06-26T12:26:54.990 に答える
1

サーバーで例外が発生すると、500 内部サーバー エラーが返されます。ActiveRecord::RecordNotFound は例外なので、500 を返します。

于 2013-06-07T03:21:23.253 に答える