将自己的错误消息填充到grails域错误

时间:2014-07-28 11:17:38

标签: grails

我想知道,如果(以及如何)我可以在验证之后(或之前)向域对象附加一些自己的错误消息。

我的意图是,我必须在表格中查看上传的文件以获取某些属性(图像大小等),如果出现问题,我想添加一条错误消息,该消息显示在通常的grails中# 34; .hasErrors"循环。

(我认为我需要有可能在某些跨域检查失败中表达错误......)

提前致谢, 苏珊。

2 个答案:

答案 0 :(得分:2)

您可以按照errors docs中的说明添加自定义验证错误,如下所示:

class SampleController {

def save() {
  def sampleObject = new SampleObject(params)
  sampleObject.validate()

  if(imageSizeIsTooBig(sampleObject)) {
    sampleObject.errors.rejectValue(
      'uploadedFile',
      'sampleObject.uploadedFile.sizeTooBig'
    )    
}

private def imageSizeIsTooBig(SampleObject sampleObject) {
  // calculation on sampleObject, if size is too big
}

也许,您甚至可以使用custom validator处理您的案例,因此您可以调用validate()一次,并确保所有约束都得到满足。

答案 1 :(得分:0)

这是一个带有自定义域错误的真实示例:

def signup(User user) {
    try {
        //Check for some condition
        if (!params.password.equals(params.passwordRepeat)) {
            //Reject the value if condition is not fulfilled
            user.errors.rejectValue(
                    'password',
                    'user.password.notEquals',
                    'Default message'
            )
            //Throw an exception to break action and rollback if you are in a service
            throw new ValidationException('Default message', user.errors)
        }
        //Continue with your logic and save if everything is ok
        userService.signup(user)
    } catch (ValidationException e) {
        //Render erros in the view
        respond user.errors, view:'/signup'
        return
    }
}