This feature of Grails 2.3.0 has made my day. I can already see lot of scope of refactoring my controller code and make it more concise. Till date the usual of writing code inside Grails controllers was to make a service call and put that inside try/catch block and handle each exception inside the controller. Imagine doing this for almost every action and you will have lot of repeated code which doesn’t follow the DRY prinicple. Obviously you can make some hacks there but there was no standard way of doing it in Grails. Old way of writing code was :

Class SomeController {

	def firstAction(){
		try{
			someService.someMethod()
		}catch(SQLException s){

		}catch(NullPointerException npe){

		}catch(Exception e){

		}
	
	}

	def secondAction(){
		try{
			someService.someMethod()
		}catch(SQLException s){

		}catch(NullPointerException npe){

		}catch(Exception e){

		}
	
	}
}

You can see that for exception handling catch blocks are being repeated and we usually add a logging message there. With Grails 2.3.0 it has been made much easier to handle exceptions inside controllers. Details are mentioned on Grails website. In simple terms you have to keep following in mind :

1. Controller can declare a method which accepts argument type of either java.lang.Exception or any subclass of java.lang.Exception then this method will be invoked incase an excpetion occurs anywhere in controller.

2. The excpetion handler methods can have any valid name. Decision to call method will be made based on argument and it has nothing to do with name.

3. These methods will have some power as any action inside a controller. They can render, redirect etc

4. These type of methods injected using meta magic are not supported as of now. They should be available at compile time.

Example below :

Class SomeController {

	def firstAction(){
		someService.someMethod()
	}

	def secondAction(){
		someService.someMethod()
	}

	def handleSQLException(SQLException s){
		/*
			This will be called in case of SQLException. 
			You can use render here
		*/
		render "Problem with the database"
	}

	def nullPointerExceptionHandler(NullPointerException npe){
		/*
			This will be called in case of NullPointerException. 
			Naming of method doesn't matters.
			You can use redirect.
		*/
	        redirect controller: 'error', action: 'dataError'
	}

	def exceptionHandler(Exception e){
		/*
			This will be called in case of generic Exception. 
			Naming of method doesn't matters.
			You can pass a model.
		*/
		['error':'A generic error happenned which is sad']
	}
}

A nice way of using this feature is to create one abstract class which contains all exception handler methods and extend your controller with that class. If you know a better way please feel free to share.