【问题标题】:populating own error-messages to the grails domain errors将自己的错误消息填充到 grails 域错误中
【发布时间】:2020-06-15 05:30:15
【问题描述】:

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

我的意图是,我必须在表单中检查上传的文件的某些属性(图像大小等),如果有问题,我想添加一条错误消息,显示在通常的 grails 中“。 hasErrors”循环。

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

提前致谢, 苏珊。

【问题讨论】:

    标签: grails


    【解决方案1】:

    您可以按照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() 一次并确保所有约束都得到满足。

    【讨论】:

    • 我收到了这个错误:方法抛出了 'org.springframework.beans.NotReadablePropertyException' 异常。尝试制作时: userCommand.errors.rejectValue( 'uploadedFile', 'sampleObject.uploadedFile.sizeTooBig'
    • 所以我使用了reject而不是rejectValue
    【解决方案2】:

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

    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
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-07-14
      • 2011-11-27
      • 1970-01-01
      • 2011-03-16
      • 2014-01-29
      • 1970-01-01
      • 2010-12-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多