1
1

More than 5 years have passed since last update.

[Grails]データバインディング(エラー制御編)

Posted at

前提条件

  • アプリケーション名は bindingtes
  • ローカルホストで動作させる。
  • ポートは8080

型変換エラー(アクション引数)

サンプルソース

package bindingtest

class HogeController {
    def actionTest(String name, Integer age) {
        render """
            errors.hasErrors():${errors.hasErrors()}<br />
            errors.errorCount:${errors.errorCount}<br />
            errors.getFieldError:${errors.getFieldError("age")}<br />
        """
    }
}

errosプロパティ

  • errors.hasErrors()
  • errors.errorCount
  • errors.getFieldError('FIELD_NAME')

実際の使い方

http://localhost:8080/bindingtest/hoge/actionTest/?name=koji&age=abcにアクセスすると、ageはアクション引数としてIntegerに自動変換されるが、その際にabcはIntegerに変換できずにエラーになる。
そのエラーがerrorsプロパティで補足できる。

メモ

アクション引数でのエラーは基本的に型変換での変換エラーのみのはず。
アクション引数に値が渡されなかった場合は、単純にnullが入るのでerrorsプロパティには何もセットされない。
例えばhttp://localhost:8080/bindingtest/hoge/actionTest/?name=kojiはageがセットされていないけど、errorsプロパティには何も入らない。

型変換エラー(ドメイン)

サンプルソース

package bindingtest

class HogeController {
    def domainTest(){
        def hoge = new Hoge(params)
        if(hoge.hasErrors()) {
            render "Error value : ${hoge.errors.getFieldError("age").rejectedValue}"
        }
    }
}

実際の使い方

http://localhost:8080/bindingtest/hoge/domainTest/?name=koji&age=abcにアクセスすると、 Error value : abc と表示される。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1