Monday, April 23, 2012

When GlassFish Stomps On Your JSON

Funny thing about learning new technologies and stacks, you run into all kinds of hard to diagnose problems. Here's one that I ran into that took a few days to figure out.

The Problem

The stack I'm working on right now is a Backbone front end with a Grails back end running on Glassfish. The thing about Backbone is since everything is in Javascript, you do a lot of jQuery calls to get/update content. One of the things to consider when doing that is error handling.

In one of my Backbone views, I'm issuing an update via a button click. This sends a post up to the server and if there's a problem, it's supposed to return some JSON as an error:

If there's an error, it gets handled by a utility written to handle errors from the Grails stack:

I was testing the error handling which worked fine on my box but when it would get deployed to GlassFish, the errors weren't happening. I looked at the response coming back from the server and the JSON was in it but right behind it was this big chunk of HTML from GlassFish:

So what the hell? Now GlassFish has decided in its infinite wisdom to add to my JSON? I searched and searched for some kind of setting to change to make it not do that. Guess what, didn't find it. The controller code I was calling to was simple enough:

Why wasn't it just giving me the JSON? Also, why was it working through the Grails stack on my box?

Select Isn't Broken

Turns out I need to learn more about HTTP content headers. I gave up on configuring GlassFish, walked away from the problem for a while and then one day it dawned on me: in Grails, if you use render without specifying the content type it's just going to assume you're sending HTML. I made one minor tweak by specifying the content type and boom, no GlassFish in my JSON:

Hope this helps someone.