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 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. 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.