Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a specific http status code in Rails

How do you return 503 Service Unavailable in Rails for the entire application?

Also, how do you do the same for specific controllers?

like image 577
Sathish Manohar Avatar asked Jan 17 '12 05:01

Sathish Manohar


People also ask

How do I find HTTP return code?

Just use Chrome browser. Hit F12 to get developer tools and look at the network tab. Shows you all status codes, whether page was from cache etc.

Which annotation is used for returning HTTP status code?

Returning Response Status Codes with @ResponseStatus This annotation takes as an argument, the HTTP Status Code, to be returned in the response.

What HTTP status code will you return to a client running into rate limiting?

The HTTP 429 Too Many Requests response status code indicates the user has sent too many requests in a given amount of time ("rate limiting"). A Retry-After header might be included to this response indicating how long to wait before making a new request.


3 Answers

You can use head

head 503
# or
head :service_unavailable
like image 146
Sergio Tulentsev Avatar answered Sep 28 '22 22:09

Sergio Tulentsev


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
like image 38
iwasrobbed Avatar answered Sep 28 '22 23:09

iwasrobbed


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.

The render head 503 does not seem to be working with the above statement.

like image 45
Frank Gracias Avatar answered Sep 28 '22 22:09

Frank Gracias