Fork me on GitHub

September 6, 2009

Handling XML/JSON Errors in Rails

Post moved to

The first time I run into this, I was just feeling so upset. I wasn't in a "railsy" mood for a while, my colleague posted an incorrectly formatted xml to our staging server and told me he got 500. No way, I said !
Slap - in my face, nothing useful in the logs, it was happening ...

My ruby-ninja sense came up with the following :

Of course it needs to check in a before filter for request.env['EXCEPTION'] to be re-raised if found ...

Few months later, I've put together a plugin to handle XML/JSON parse errors and treat parsing exceptions like other raised errors, an example is more than 1024 words :

Please realize, that even if exceptions are treated equal those related to request parameter parsing probably caused some parameters to be not available in your controller code (you obviously can't access params[:user] when posting an invalid user XML snippet) and thus you should NOT recover from those !

The primary intent of this plugin is to be able to customize the default HTTP 500 status returned by Rails.

UPDATE: Starting Rails 2.3.5 ActiveSupport::JSON::ParseError is gone, you'll have to use the JSON backend's parse error for rescuing (available at ActiveSupport::JSON.parse_error).

UPDATE: As Rails 3.0.0 did not really update the code that handles parameter parsing errors, the plugin has been reviewed to work with 3.0.0 (and is threadsafe).

See the plugin at

1 comment:

  1. I ran into an exception using request_exception_handler with rails 2.3.5. For the most part, it works fine, however, when sending an invalid xml string, e.g. "test" without tags something triggers en exception in the initializer. Line 30 is:

    out = parse_formatted_parameters_without_exception_handler(env)

    And the exception is:

    NoMethodError (undefined method `name' for nil:NilClass):
    config/initializers/request_exception_handler_init.rb:30:in `parse_formatted_parameters_with_exception_handler'

    Any ideas on what may be triggering it? Thanks!