Is it possible to catch / handle exceptions thrown from a Grails controller? Aop?

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

Is it possible to catch / handle the exception caused 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 can handle it.

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

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

+5
source share
3 answers

How about this amazing template.

http://grails.1312388.n4.nabble.com/Possible-to-get-the-errorhandler-calling-a-controller-closure-td1354335.html

class UrlMappings {
    static mappings = {
      "/$controller/$action?/$id?" {
          constraints { // apply constraints here  }
      }
    "500"(controller:'system', action:'error')
}

class SystemController {
    def error = {
        // Grails has already set the response status to 500

        // Did the original controller set a exception handler?
        if (request.exceptionHandler) {
            if (request.exceptionHandler.call(request.exception)) {
                return
            }           
            // Otherwise exceptionHandler did not want to handle it
        }       
        render(view:"/error")        
    }
}

class MyAjaxController {

    def beforeInterceptor = {
        request.exceptionHandler = { ex ->
            //Do stuff           
            return true
        }
    }

    def index = {
        assert false
    }
}
+5

Grails.

, UrlMapping :

"500" (controller: "foo", action: "bar", exception: FooBarException)

, , . , .

, . , Google " + ".

: ErrorController. [ "exception" ] , ( , before). - , fatalError.

+2

Grails "" , , , . :

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

, , , , , .

+1

All Articles