简体   繁体   English

在Rails中返回特定的http状态代码

[英]Return a specific http status code in Rails

How do you return 503 Service Unavailable in Rails for the entire application? 您如何为整个应用程序返回503服务在Rails中不可用?

Also, how do you do the same for specific controllers? 另外,您如何对特定控制器执行相同操作?

You can use head 你可以用head

head 503
# or
head :service_unavailable

For the entire application: 对于整个应用程序:

# ApplicationController
before_filter :return_unavailable_status

private
  def return_unavailable_status
    render :nothing => true, :status => :service_unavailable
  end

If you wanted a custom error page, you could do: 如果要自定义错误页面,可以执行以下操作:

render 'custom_unavailable_page', :status => :service_unavailable    

If you don't want it for specific controllers: 如果您不希望将其用于特定控制器:

# SomeController
skip_before_filter :return_unavailable_status

The following works for me: 以下对我有用:

format.any { render :json => {:response => 'Unable to authenticate' },:status => 401  }

The :response for the HTML response just in case it's accessed from the browser. HTML响应的:response ,以防万一它是从浏览器访问的。

The render head 503 does not seem to be working with the above statement. 渲染头503似乎不适用于以上陈述。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM