【问题标题】:Is it possible to catch / handle exceptions thrown from a Grails controller? Aop?是否可以捕获/处理从 Grails 控制器抛出的异常?哎呀?
【发布时间】:2009-11-19 22:06:54
【问题描述】:
class MyController {
   def myAction = {
      throw new MyException("Test")
   }
}

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

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

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

【问题讨论】:

    标签: grails exception-handling aop


    【解决方案1】:

    这个很棒的模式怎么样。

    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
        }
    }
    

    【讨论】:

    • SystemController 处理异常...漂亮!
    【解决方案2】:

    有一种方法可以使用 Grails 进行常见的异常处理。

    首先,在您的 UrlMapping 文件中,您可以如下声明映射:

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

    但请记住,这会使您的日志文件充满错误消息。根据具体的用例,这可能是也可能不是您想要的。

    如果您不想产生错误消息,您可以使用插件。将“声明性异常处理+grails”放入google后应该会弹出。

    就个人而言,我使用以下方法:我将所有异常异常都路由到 ErrorController。在那里我可以访问请求[“异常”],以及一些附加参数,如原始控制器和操作(我使用前置过滤器手动将此信息放入请求属性映射)。然后我决定采取适当的步骤 - 通常在原始控制器上调用一些操作,比如 fatalError。

    【讨论】:

      【解决方案3】:

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

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

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

      【讨论】:

      • 谢谢大哥!它并没有达到我想要的程度,但它是为了摆脱 try / catch。
      猜你喜欢
      • 2012-12-22
      • 1970-01-01
      • 1970-01-01
      • 2015-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-10
      • 1970-01-01
      相关资源
      最近更新 更多