How to handle exception in format.xml

I am developing an API for my application.

Here is the standard show method.

def show

@city = City.find(params[:id], :include => :state)

respond_to do |format|





For a browser based action if the params[:id] is missing then ActiveRecord::RecordNotFound exception is raised which I let Rails handle. This results in public/404.html.

However in API I need to catch the exception and then I need to return an xml with the error message. What is the best way to handle that. Any example will be helpful

Right now even if I catch the exception then after catching the exception I need to process two different ways for html and xml. Secondly I need to know if I am processing html or xml. How do I find out if I am handing html or xml. Is there a utility method?

  • Neeraj

Look at the bottom of the create or update methods in the controller.
Both have examples of handling errors that should serve as examples.

The update scenario doesn't handle if
@city = City.find(params[:id]) throws ActiveRecrod::RecordNotFound

I want to return an xml stating that no record was found for the given

I can catch the exception but am not sure what is the best way to handle
this case when I must return an xml response every single time.

If that's kind of a global rule you can easily program a catchall with rescue_from in Rails 2, respond_to is available in the handler as well.

-- fxn