See the light - agile, industrial strength, rapid web application development made easy

(Quick Reference) # 7.1.13 Declarative Controller Exception Handling - Reference Documentation Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith, Lari Hotari Version: 2.3.8 ## 7.1.13 Declarative Controller Exception Handling Grails controllers support a simple mechanism for declarative exception handling. If a controller declares a method that accepts a single argument and the argument type is `java.lang.Exception` or some subclass of `java.lang.Exception`, that method will be invoked any time an action in that controller throws an exception of that type. See the following example.

    // grails-app/controllers/demo/DemoController.groovy
    package democlass DemoController {    def someAction() {
            // do some work
        }    def handleSQLException(SQLException e) {
            render 'A SQLException Was Handled'
        }    def handleBatchUpdateException(BatchUpdateException e) {
            redirect controller: 'logging', action: 'batchProblem'
        }    def handleNumberFormatException(NumberFormatException nfe) {
            [problemDescription: 'A Number Was Invalid']
        }
    }
That controller will behave as if it were written something like this...

    // grails-app/controllers/demo/DemoController.groovy
    package democlass DemoController {    def someAction() {
            try {
                // do some work
            } catch (BatchUpdateException e) {
                return handleBatchUpdateException(e)
            } catch (SQLException e) {
                return handleSQLException(e)
            } catch (NumberFormatException e) {
                return handleNumberFormatException(e)
            }
        }    def handleSQLException(SQLException e) {
            render 'A SQLException Was Handled'
        }    def handleBatchUpdateException(BatchUpdateException e) {
            redirect controller: 'logging', action: 'batchProblem'
        }    def handleNumberFormatException(NumberFormatException nfe) {
            [problemDescription: 'A Number Was Invalid']
        }
    }
The exception handler method names can be any valid method name. The name is not what makes the method an exception handler, the `Exception` argument type is the important part. The exception handler methods can do anything that a controller action can do including invoking `render`, `redirect`, returning a model, etc. The exception handler methods are inherited into sublcasses so an application could define the exception handlers in an abstract class that multiple controllers extend from. Exception handler methods must be present at compile time. Specifically, exception handler methods which are runtime metaprogrammed onto a controller class are not supported. | Quick Reference (hide)