views:

409

answers:

1
class MyController {
   def myAction = {
      throw new MyException("Test")
   }
}

Is it possible to catch / handle the exception thrown by the code above? The following url-mapping kinda works, but it causes the exception to be logged, which is annoying because in my case I'm able to handle it.

"500"(controller: "error", action: 'myExceptionHandler', exception: MyException)

Why don't I wrap the code that might throw an exception in try / catch? Well I have several actions that might throw the same exception. Wrapping each and every one of them in try / catch violates the DRY-principle.

+1  A: 

There may be a more "correct" method of doing this in Grails, but write a method that takes in a closure and handles the exception if needed. Then your code would be something like:

class MyController {
   def myAction = {
      handleMyException {
         throw new MyException("Test")
      }
   }
}

It introduces a line of code, but the exception handling code is at least all in one place, and you have the benefit of handling the exception in the action where it was thrown.

Jean Barmash
Thank's man! It's doesn't quite take it as far as I want to, but it's to get rid of the try / catch.
Kimble