Handling Exceptions in Grails

03 / Jan / 2022 by Sumit Navin 0 comments

Daahh !! Who doesn’t know how to handle exceptions. A simple try-catch block would do the job. But think of so many methods where we will have to keep the same code of catching exceptions and then creating the desired response.

Hmm, haven’t you heard of the common try-catch in the filter? Well, we can do that!

But let’s say we have a list of exceptions to handle. We will have to take care of the hierarchy and keep adding multiple catch blocks as per that since our response code will be different for the different exceptions.

From Grails 2.3.0 we can use declarative Controller Exception Handling.
All you have to do is to create a handleYourExceptoion() method in your controller. Yes, you read it right, no annotation just the method with ‘handle ‘ as the prefix, like below (code is in Groovy).

Handle

And let’s say you have your own exception to handle just create a method like below (code is in Groovy).

Handle

Now, will you be writing these handlers in every Controller? Of course not. Create an AbstractController, and extend this class in your Controller where you want to handle exceptions. Like below (code is in Groovy).

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *