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 中,而不是 rails-api。希望能想出更好的东西,但到目前为止我只是做了(如上所示):

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

如果您将 Rails 的“仅在生产环境中救援并返回 404”功能视为方便的默认设置,我想这是合理的,但是当您更关心状态代码时,您需要让您的手(和代码)有点脏。

于 2013-06-26T12:26:54.990 回答
1

每当服务器出现异常时,都会返回 500 内部服务器错误。ActiveRecord::RecordNotFound 是一个例外,所以它返回 500。

于 2013-06-07T03:21:23.253 回答