0

我调用了一个创建父子记录的服务。如果发生错误,服务将引发 RuntimeException。RuntimeExceptionis 被控制器捕获,然后重定向回 gsp。但是没有呈现错误。

在这种情况下,我猜是控制器,因此 gsp 并没有真正与对象有关,因为一切都在服务中完成。那么如何呈现错误呢?

简单数据输入 GSP

<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Sample title</title>
  </head>
  <body>
    <h1>Add A Record</h1>

<g:hasErrors bean="${parent}">
    <div class="errors">
        <g:renderErrors bean="${parent}" as="list" />
    </div>
</g:hasErrors>
<g:hasErrors bean="${child}">
    <div class="errors">
        <g:renderErrors bean="${child}" as="list" />
    </div>
</g:hasErrors>  
  <g:form action="add" name="doAdd">
    <table>
      <tr>
        <td>
          Parent Name
        </td>
        <td>
          Child Name
        </td>
      </tr>
      <tr>
        <td>
      <g:textField name="parentName"  />
      </td>
      <td>
      <g:textField name="childName" />
      </td>
      </tr>
      <tr><td><g:submitButton name="update" value="Update" /></td></tr>
    </table>
  </g:form>
</body>
</html>

控制器

   class AddrecordController {

    def addRecordsService

    def index = {
        redirect action:"show", params:params
    }

    def add = {
        println "do add"


        try {
            addRecordsService.addAll(params)
        } catch (java.lang.RuntimeException re){
           println re.message
            flash.message = re.message
        }
        redirect action:"show", params:params

    }

    def show = {}

}

服务

  class AddRecordsService {

    static transactional = true



    def addAll(params) {
        def Parent theParent =  addParent(params.parentName)
        def Child theChild  = addChild(params.childName,theParent)
    }

    def addParent(pName) {
        def theParent = new Parent(name:pName)
        if(!theParent.save()){
            throw new RuntimeException('unable to save parent')
        }

        return theParent
    }

    def addChild(cName,Parent theParent) {
        def theChild = new Child(name:cName,parent:theParent)

        if(!theChild.save()){
            throw new RuntimeException('unable to save child')
        } 
        return theChild
    }

}
4

1 回答 1

0

您需要以某种方式获取对无效对象的引用并通过模型将其传递给视图,因此我将扩展 RuntimeException 并添加字段以包含具有验证错误的对象,例如

}catch(MyCustomException m){
render view:'show', model:[parent:m.getParent(), child:m.getChild()]
}

使用 Parent.withTransaction 而不是通过 RuntimeExceptions 自动回滚,整个练习可能会更容易。然后,如果存在验证错误,您可以手动回滚事务并仅返回对象,而不必将它们包含在异常中。

于 2009-10-30T00:50:27.383 回答