Hi,
I’m putting together a RESTful API that I would like to play nice with
ActiveResource. I’ve got things mostly working, but I’m beginning to
stumble around error handling and I’m seeking some thoughtful input.
Here’s some context:
(For a detailed look at the issue I’m contemplating see:
http://www.oreillynet.com/onlamp/blog/2003/12/restful_error_handling.html)
Let’s say that I have a REST controller containing code that looks like
this:
def create
@book = @book(params[:book])
respond_to do |format|
if false @book.save
format.xml { head :created, :location => book_url(@book) }
else
format.xml { head 400, :xml=> ErrorCode.new(20, “Save
failed.”).to_xml }
end
end
end
(note, I’m deliberately forcing a failure response with ‘if false’ )
When I execute this method via CURL, I get following (correct, I
believe) response:
#—
t$ curl -i -X POST http://0.0.0.0:3001/books.xml
HTTP/1.1 400 Bad Request
Connection: close
Date: Wed, 11 Apr 2007 19:46:11 GMT
Set-Cookie: _adiserver_session_id=dbe7f61d877a041c3d5d49c29d0086e5;
path=/
Status: 400 Bad Request
Xml: <?xml version="1.0" encoding="UTF-8"?>
20
Could not save book
save failed.
#—
This response looks correct me because it has:
- an HTTP Status code
- some descriptive XML
Seeing this, I expect that ActiveResource should be happy…
but, alas, when doing a @book.save over ActiveResource (console), I get:
@book.save
ActiveResource::ResourceNotFound: Failed with 404
from/script/…/config/…/config/…/vendor/rails/
activeresource/lib/active_resource/connection.rb:92:in `handle_response’
etc…
Now I would expect to get ‘false’ and/or the the XML containing the
error information that I’ve constructed.
–OR–
My questions are these:
- What does ActiveResource expect in the case of failed operation?
- In the event of a failed request, how does AR get access to the
supplemental XML that is sent? Is this possible? - Are some of my assumptions incorrect?
Perhaps “ActiveResource::ResourceNotFound” is an exception that I need
to handle in the following manner:
begin
@book.save
rescue
[…could not save code here …]
end
I look forward to your thoughtful guidance.