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()]
}

この演習全体は、RuntimeExceptions による自動ロールバックの代わりに Parent.withTransaction を使用すると簡単になる場合があります。次に、検証エラーが発生した場合は手動でトランザクションをロールバックし、オブジェクトを例外に含める代わりにオブジェクトを返すことができます。

于 2009-10-30T00:50:27.383 に答える