The other day I had to go to support.microsoft.com, and I got a raw error page:
That made me think that it’d be a good idea to blog how to create a custom error handler in Grails. By “handler,” I mean more than just a .gsp that shows an “Oops” message, instead of a stack trace, when GrailsUtil.environment is “production.” I mean one that:
Shows an “Oops” message, instead of a stack trace, when GrailsUtil.environment is “production.” ( )
Invokes a controller method, allowing me to “do stuff” (log, e-mail administrators, etc.) when there’s an error
Gracefully handle a subsequent nested error within the controller
So here’s what I do:
Creating a environment-specific views
First, I whip up a quick ErrorController that renders a ‘development’ view in development, and a ‘production’ view in production:
Then, I create development and production specific views in views/error:
Last, I tell UrlMappings.groovy to use my ErrorController instead of the stock errors.gsp view:
Using my controller method to ‘do stuff’ with the exception
Within my controller method, the exception is available in request.exception, letting me log it, e-mail myself, or do whatever I want. In a full-bore application, it might be a good idea to wrap this logic up in a service.
Please, read the next section, or you may end up in a world of hurt.
“Doing stuff” without destroying your server
If you’re anything like me, it’s inevitable that your error handling “stuff” will one day throw an error. That’s bad, because it’d re-invoke the error handler…which’d re-invoke the stuff…which’d throw another error…which’d…you get the idea. Lost thread, server crash, bad day altogether.
I’m a simpleton, so I opt for an easy way out of this that tries/catches both “doing stuff” and rendering the appropriate view, showing a third very basic, “geez-this-should-never-fail” view:
Joe Rinehart's been developing software for Web, mobile, and desktop since 1998. While he mainly now works in Java, Grails, and HTML5, he has a long history of community involvement in the Flash, Flex, and ColdFusion space. As a published author and award-winning speaker, he's bringing his skills to CompileDammit to help users new to Grails and Java. When he's not coding, he's either spending time with his family or feeding an appetite for endurance mountain bike racing. (8/9/2012 update: He's now either spending time with his family or getting over a huge knee injury caused by endurance mountain bike racing.)