Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3: How to return errors in a JSON request?

How can I return a 800, 404, etc error when a user makes a JSON/XML request to my API?

I've tried

error 404, {:error => "ERror".to_json } 

with no success.

Also, I've tried to put a "respond_to" but it doesn't work as well (it duplicates the respond_to and gives error).

Thanks

like image 844
donald Avatar asked May 14 '11 20:05

donald


1 Answers

The same way you return such errors with html, it's part of the HTTP Header.

render json: @myobject, status: :unprocessable_entity 

Update, response to comment:

You can get all the status codes from Rack. Rails passes the symbolized status to Rack

Rack::Utils.status_code(options[:status]) 

which simply matches the symbol to the list of status (the strings are converted to symbols) Here is the smoking fresh list: https://github.com/rack/rack/blob/master/lib/rack/utils.rb#L575-L638

Scroll a bit lower and you'll see the status_code method. It's fun to read the source code!

like image 152
oma Avatar answered Sep 21 '22 04:09

oma