Fork me on GitHub

September 6, 2009

Handling XML/JSON Errors in Rails

Post moved to http://log2.kares.org/post/59891229302/handling-xml-json-errors-in-rails

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 http://github.com/kares/request_exception_handler.