Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return correct HTTP error codes from Ruby on Rails application

I have RoR 3.0 web application which is acting as an OAuth API provider. Now, in API I'd like to return correct HTTP error codes to the API consumer. How do I do this?

Here is example:

def destroy_oauth     @item = Item.find(params[:id])     if([email protected]? && @item.user_id == current_user.id)         @item.destroy         respond_to do |format|                 format.js                 format.xml         end     else         raise ActionController::RoutingError.new('Forbidden')     end end 

So, in case of error I'm trying to return Forbidden 403 code. Still, when running this I'm getting always 404 Not Found returned. How do I return the correct code?

Or is this somehow webserver configurable thing?

like image 422
Alexander Savin Avatar asked Feb 03 '12 14:02

Alexander Savin


2 Answers

When you're just giving a status code and there is no body, a convenient way is

head 403 

This method also accepts the symbolic names for status codes, such as

head :forbidden 
like image 192
Frederick Cheung Avatar answered Oct 05 '22 18:10

Frederick Cheung


You should render page with correct status.

render(:file => File.join(Rails.root, 'public/403.html'), :status => 403, :layout => false) 
like image 33
Sandip Ransing Avatar answered Oct 05 '22 17:10

Sandip Ransing