2009-10-29 53 views
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 
    } 

} 

回答

0

您甲肾上腺素ed以某种方式获得对该无效对象的引用,并通过模型将其传递给视图,以便扩展RuntimeException并添加字段以包含带有验证错误的对象,例如

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

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