Grails 从服务中呈现错误

Grails 从服务中呈现错误,grails,grails-validation,Grails,Grails Validation,我调用一个创建父记录和子记录的服务。如果发生错误,服务将抛出RuntimeException。运行时异常被控制器捕获,然后重定向回gsp。但是错误并没有被呈现出来 在这种情况下,我猜控制器和gsp实际上没有任何关于对象的信息,因为一切都是在服务中完成的。那么,如何呈现错误呢 简单数据输入普惠制 服务 您需要以某种方式获取对无效对象的引用,并通过模型将其传递给视图,这样我就可以扩展RuntimeException并添加字段来包含存在验证错误的对象,例如 }catch(MyCustomExcepti

我调用一个创建父记录和子记录的服务。如果发生错误,服务将抛出RuntimeException。运行时异常被控制器捕获,然后重定向回gsp。但是错误并没有被呈现出来

在这种情况下,我猜控制器和gsp实际上没有任何关于对象的信息,因为一切都是在服务中完成的。那么,如何呈现错误呢

简单数据输入普惠制

服务


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

}catch(MyCustomException m){
render view:'show', model:[parent:m.getParent(), child:m.getChild()]
}
使用Parent.withTransaction而不是通过运行时异常自动回滚,整个练习可能会更容易。然后,如果出现验证错误,您可以手动回滚事务,只返回对象,而不必将它们包含在异常中

   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
    }

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