Tuesday, April 13, 2010

Custom Grails Error Handling

Error handling in your Grails app is especially important, as Groovy is a non-checked language -- methods need not declare a throws clause. While UrlMappings.groovy provides a default page for general 500 errors, in our application, we'd like to display different error pages in different situations.

There are several approaches to this problem. One solution is to separate error handling by exception class. This can be done by modifying Bootstrap.groovy

exceptionHandler is an instance of GrailsExceptionResolver, and can be auto injected. Note the last entry is needed for default handling.

Also, be sure to remove the "500" entry from UrlMappings.groovy, as interferes with the definitions here.

class BootStrap {
def exceptionHandler

def init = {
exceptionHandler.exceptionMappings = [
'SpecialException' : '/myController/someAction',
'java.lang.Exception' : '/error'
]
}
}



Another approach is to modify the handling in UrlMappings.groovy. By default, the "500" entry points to error.gsp in the views directory, but it can be changed to another view, or a controller with optional action specified.
"500"(controller:'myController', action:'handleExceptions')

No comments:

Post a Comment