3

I'm trying to serve different responses in Grails when an error 500 happens depending on the format of the request.

I've created an ErrorController and I'm using it in the URLMappings but I'm not getting the right request format:

def handle() {
    withFormat {
        html {
            response.status = 500
            render(view:'/errors/serverError')
        }
        json {
            response.setContentType "application/json; charset=utf-8"
            response.status = 500
            ApiResponse apiResponse = new ApiResponse(
                meta: new ApiMeta(
                    code: 500,
                    errorType: "Whatever",
                    msgs: ["${request.exception}"]
                )
            )
            render apiResponse as JSON
    }
    }
}

The response is always in html. Also tried with 'request.withFormat' with the same results.

What I'm missing here?

chozero
  • 411
  • 6
  • 12

2 Answers2

1

I do not have enough info to verify if this is really the reason, but it could look like a MIME type issue. Is json configured correctly as MIME type in your Config.groovy? Does your client accept your MIME type. See this link for reference http://grails.org/doc/2.1.0/guide/single.html#contentNegotiation

John Doppelmann
  • 544
  • 4
  • 15
  • JSON is included as MIME in Config.groovy (Grails 2.1.1): json: ['application/json','text/json'], Also I've been able to detect format in other controller actions. – chozero Sep 24 '12 at 08:20
  • It was indeed related to the MIME type. I wasn't accepting format in the "Accept" header. I changed 'grails.mime.use.accept.header' to true in Config.groovy and it works. – chozero Oct 02 '12 at 17:20
1

I'm not sure if this can solve your problem...but try error handling in URLMapping as you can see in http://grails.org/doc/latest/guide/theWebLayer.html#mappingToResponseCodes

You could catch any exception from your actions and throws an exception as JSONException when format request is JSON.

"500"(controller: "error", action: "handleJsonException", exception: JSONException)
"500"(controller: "error", action: "handleHtmlException")
semurat
  • 11
  • 1
  • I've tried this solution but it didn't work. Adding a handler for JSONException will work but only if the exception caught is of that type, for example a parsing error. Thanks anyway :) – chozero Oct 02 '12 at 14:59