是否可以捕获/处理从Grails控制器抛出的异常?AOP?

Kim*_*ble 5 grails aop exception-handling

class MyController {
   def myAction = {
      throw new MyException("Test")
   }
}
Run Code Online (Sandbox Code Playgroud)

是否可以捕获/处理上面代码抛出的异常?以下url-mapping有点工作,但它会导致异常被记录,这很烦人,因为在我的情况下我能够处理它.

"500"(controller: "error", action: 'myExceptionHandler', exception: MyException)
Run Code Online (Sandbox Code Playgroud)

为什么我不包装可能在try/catch中引发异常的代码?好吧,我有几个行为可能会抛出相同的异常.在try/catch中包装它们中的每一个都违反了DRY原则.

and*_*ard 5

这个令人敬畏的模式怎么样?

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
    }
}
Run Code Online (Sandbox Code Playgroud)


Jea*_*ash 1

在 Grails 中可能有更“正确”的方法来执行此操作,但是编写一个接受闭包并在需要时处理异常的方法。那么你的代码将是这样的:

class MyController {
   def myAction = {
      handleMyException {
         throw new MyException("Test")
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

它引入了一行代码,但异常处理代码至少都在一个地方,并且您可以在抛出异常的操作中处理异常。