Question

I am using Grails 2.3 to create a REST API, and I want a better way to handle rendering error responses as a JSON response. What is have currently is a package of exceptions that all have a toJSON method. So all my controller methods wrap everything in the same try/catch blocks and render any error responses the same way.

What I really want is to have an uncaught exception handler that does all this without having to wrap everything in try/catch. So if there's an uncaught exception, it'll automatically convert the exception into JSON, set the appropriate status code, and write and flush the response.

Given all that, here's the actual question: So the first question is: is this a dumb idea?

Since Grails handles all the thread pooling, I think I would need to register my handler at the beginning of every api call. Should I do this in the beforeInterceptor closure of each controller?

Also, how would I be able to access the response object from my handler in order to be able to write the proper response?

Even if someone could point me to the relevant grails classes in the docs, that would be a big help. I searched and could not find the classes where grails does this to see if I can use their existing classes instead of writing my own.

Was it helpful?

Solution

http://grails.org/doc/latest/guide/theWebLayer.html#mappingToResponseCodes might help. In essence, mapped custom ErrorController could render uncaught exceptions to JSON,

class MyJSONErrorController {
    def handleError() {
        def exception = request.exception
        // perform desired processing to handle the exception
        render exception as JSON
    }
}

Doing beforeInterceptor or try catch block in each controller seems overwhelming. As Spring framework advocated, only catch exceptions that you need handle specifically than common errors.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top