How to Handle Exception In grails Controller

Posted By : Sanjay Saini | 27-Jun-2015

Hi friends ,

Here i'm going to explain you how to handling exception in controller in grails.

Grails 2.3.0 has a feature that allow to you to use declartive Controller Exception handling, Normally We put grails controller action code  inside try/catch block and handle each possible Exception separtely for every action in controller.

Using the above approach of try/catch block for every action in controller for handling same type of exception generated lot of repeated code  that's break's the DRY Principle. 

The Usual way of  writing and Handling  Exception in grails Controller is as below :

Class DemoController {

    def demoService 

    def testActionFirst(){
        try{
            demoService.testMethodFirst()
        }catch(IOException ioex){
 
        }catch(Exception exception){
 
        }
     
    }
 
    def testActionSecond(){
        try{
            demoService.testMethodSecond()
        }catch(IOEception ioex){
 
        }catch(Exception e){
 
        }
     
    }
}

In above Example You can see that for exception handling catch blocks are being repeated . In Grails 2.3.0 it has been made much simpler to handle exceptions inside  grails controllers actions .  In simple terms you have to keep following in mind :

1.In  Controller declare a method that accepts arguments  type of  java.lang.Exception  this method will be invoked when  an excpetion occurs anywhere in controller and matching handler not found then that's method accepts all types Exception. 

2. Created Seprate method for handling differnent type of Exception and handling Exception Object pass as a Arguments.

3. Exception Handler Method have power of render, redirect etc.

Easiest Way of writing code for Exception Handling in grails 2.3.0 and above controller action  :

Class DemoController {
 
    def demoService 

    def testActionfirst(){
        demoService.testMethodFirst()
    }
 
    def testActionSecond(){
        demoService.testMethodSecond()
    }
 
    def handleIOException(IOException ioex){
        /*
           This method will be executed if any IO Exception occurs .
        */
        render "Something Went Wrong"
    }
 
    
 
    def exceptionHandler(Exception e){
        /*
           This method will be called if any unhandled Execption occurs in the code 
        */
        ['error':'Something Went Wrong ,Our Tech. Team will Analysize it shortly']
    }
}

Note : Similarly above can be used to handle many more types of Exceptions.

Thanks

 

About Author

Author Image
Sanjay Saini

Sanjay has been working on web application development using frameworks like Java, groovy and grails. He loves listening to music , playing games and going out with friends in free time.

Request for Proposal

Name is required

Comment is required

Sending message..