pedroaxl
pedroaxl

Reputation: 303

Return error message in XML response

I am working on the API of my web app. It is a Rails 2 app, and the REST API respond to XML.

For example, I need to return an error, in case it wasn't able to unsubscribe a contact from a list. So I respond with an Unprocessable Entity (422), with the error message in the XML. This is the actual code:

respond_to do |format|
  begin
    ...
    format.xml  { head :ok }
  rescue => e
    format.xml  { render :xml => e.to_s, :status => :unprocessable_entity }
  end
end

The problem is that in the other side, when someone make a requisition using ActiveResouce the error arrives with the message empty, like this:

ActiveResource::ResourceInvalid: Failed.  Response code = 422.  Response message = . 

Is there any XML structure or tag I need to put in the response, to the Response message don't be empty?

Thanks

Upvotes: 3

Views: 1989

Answers (2)

Andrew France
Andrew France

Reputation: 4879

The Rails ActiveResource Validation documentation states that it expects errors in the XML format of:

<errors><error>First cannot be empty</error></errors>

I think that's designed to come from the object validation errors hash (e.g. render :xml => record.errors). Not really sure why you would want to catch an exception though as that should indicate a far more serious problem more akin to a server error.

Upvotes: 2

Behrang Saeedzadeh
Behrang Saeedzadeh

Reputation: 47961

This doesn't look correct to me:

format.xml  { render :xml => e.to_s, :status => :unprocessable_entity }

render :xml, should be passed an XML string. Try replacing it with something like this:

format.xml  { render :xml => "<message ='#{e.to_s}'/>", :status => :unprocessable_entity }

Upvotes: 3

Related Questions