Showing posts with label Exception Handling. Show all posts
Showing posts with label Exception Handling. Show all posts

Monday, September 16, 2013

Grails Controller allow Declarative Exception Handling with Filters

I guess you can handle declarative exception from Controllers but Filters. You can use response instead to send the error code
class AuthorizationFilters {
    def filters = {
        auth(controller: '*' /* or controller name */
            action: '*' /* or action name */, invert: true) {
            before = {
                HashMap map = new HashMap();
                map.put("success", false);
                map.put("message", "Error occurred"); 
                if(1){ //If auth fails
                    response.sendError(5000) /* Custom error code */
                    response.errorMessage = "Error message to error controller";
 
                    // OR 
                    //render(status: 403);
                    //render(contentType: "text/json", text: map.toJSON());
 
                    // OR 
                    //redirect(controller: 'error', action: 'errorDisplay');
                }
                return false
            }
        }
    }
}
Above logic will render the response from ErrorController's errorDisplay action based on the UrlMapping that is provided below.
Make sure you are excluding error controller from filters.

Make sure you have the entry in UrlMappings.groovy:
"5000"(controller: "error", action: "errorDisplay")

And ErrorController.groovy:
class ErrorController {
    def errorDisplay() {
        render(status: 500); /* Change error code to 500 from custom code: 5000 */
        render("Error: "+response.errorMessage);
        //response.errorMessage would be "Error message to error controller";
        return;
    }
}