7.1.12 Declarative Controller Exception Handling - Reference Documentation
Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith, Lari Hotari
Version: 3.0.11
7.1.12 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 isjava.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'] } }
// 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'] } }
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.One way to share exception handler methods across multiple controllers is to use inheritance. Exception handler methods are inherited into subclasses so an application could define the exception handlers in an abstract class that multiple controllers extend from. Another way to share exception handler methods across multiple controllers is to use a trait, as shown below...// src/groovy/com/demo/DatabaseExceptionHandler.groovy
package com.demotrait DatabaseExceptionHandler {
def handleSQLException(SQLException e) {
// handle SQLException
} def handleBatchUpdateException(BatchUpdateException e) {
// handle BatchUpdateException
}
}
// grails-app/controllers/com/demo/DemoController.groovy package com.democlass DemoController implements DatabaseExceptionHandler { // all of the exception handler methods defined // in DatabaseExceptionHandler will be added to // this class at compile time }