【问题标题】:Missing HTTP status in the response响应中缺少 HTTP 状态
【发布时间】:2011-08-25 12:43:29
【问题描述】:

我在 Rails 3 应用程序之上构建了一个 restful api,每当找不到如下实体时,我都会引发自定义异常错误

@line = @current_account.lines.find(:first, :conditions =>{:title => line_title})
raise CustomExceptionError.new("Line not found for title: #{line_title} under your account",404) if @line.nil?

这里是 CustomExceptionError 类

class CustomExceptionError < StandardError
  attr_accessor :message, :status
  def initialize(message,status=422)
   @message = message
   @status = status
  end
  def to_s
   "#{@message}"
  end
end

这是用于处理异常的方法

def custom_error_renderer(exception = nil)
  if exception
     logger.info "Rendering 404: #{exception.message}"
  end
  error = {:error => {:message => exception ? exception.message : "Undefined error."}}
  render :json => error, :status => exception.status

结束

但是当我查看服务器日志时

18:12:09 action_controller Completed   in 18ms
18:12:09 action_controller Rendering 404: Line not found for title: dater98 under your account

日志中缺少状态码

如果我直接渲染而不是引发 CustomExceptionError

render :status => 404, :json => {:error => {:message=> "Line not found for title: #{line_title} under your account""}}

然后它返回状态码。

Completed 404 Not Found in 84ms (Views: 75.7ms)

我不知道我在这里做错了什么。有什么建议或猜测???

【问题讨论】:

  • 我无法在我的机器上复制这个问题。您如何让日志看起来像它们一样?
  • 我正在跟踪 tail -f log/development.log
  • 对我来说,这看起来不像那个输出。一方面,每行的开头 处没有时间戳。我有这个,例如:Completed 422 Unprocessable Entity in 3ms (Views: 1.5ms | ActiveRecord: 0.3ms)
  • 我没有使用活动记录。我正在使用 mongoid。

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-1.9


【解决方案1】:

如果您使用状态进行渲染,它将从您的 public/404.html 文件发送标准 404 响应。

您可以尝试删除您的 public/404.html 文件。

【讨论】:

  • 首先,它是一个 json API req/res。所以不会呈现 html 文件。请仔细阅读问题。按预期返回正确的状态代码。唯一的问题是它没有打印在日志上。
猜你喜欢
  • 2020-06-28
  • 2020-05-09
  • 2014-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多