Micronaut 中奇怪的验证错误处理
Weird validation error handling in Micronaut
我有一个控制器操作来为我的 React 前端服务。它需要特殊格式的验证消息:
@Transactional
@Post( uri = '{/id}', consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON )
HttpResponse save( @PathVariable @Nullable Long id, @Body Map body ){
def o = bindFromIdAndBody id, body
if( o.save( flush:true ) ){
log.info "version >> $o.version"
HttpResponse.ok o
}else{
log.info '-------------------------'
List errors = o.errors.fieldErrors.collect{ FieldError fe ->
fe.codes.findResult{ String c ->
messageSource.getMessage c, fe.arguments, null, Locale.default
} ?: fe.codes.last()
}
log.info "save failed for $o: $errors"
HttpResponse.badRequest( errors:errors )
}
}
当我调用该操作时,我在我的客户端中得到 400 Bad Request
,但我看到的不是 { errors:[ {..}, {..}, {..} ]
样式 JSON,而是:
{
"message":"Validation Error(s) occurred during save() : Field error in object ... default message [Property [{0}] of class [{1}] cannot be blank]\r\n",
"path":"fullName",
"_links":{"self":{"href":"/person/42","templated":false}}
}
而且 else{}
块从未到达,我没有得到任何进一步的日志。
有什么提示吗?
看来,在 Micronaut 的 GORM 配置中是通过
完成的
compile 'io.micronaut.configuration:micronaut-hibernate-gorm'
默认情况下 failOnError
设置为 true
。这导致 ValidationException
被扔到 save()
而不是填充 o.errors
。
为了解决这个问题,我添加了行
grails.gorm.failOnError: false
我的application.yml
,现在它运行得很好。
我有一个控制器操作来为我的 React 前端服务。它需要特殊格式的验证消息:
@Transactional
@Post( uri = '{/id}', consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON )
HttpResponse save( @PathVariable @Nullable Long id, @Body Map body ){
def o = bindFromIdAndBody id, body
if( o.save( flush:true ) ){
log.info "version >> $o.version"
HttpResponse.ok o
}else{
log.info '-------------------------'
List errors = o.errors.fieldErrors.collect{ FieldError fe ->
fe.codes.findResult{ String c ->
messageSource.getMessage c, fe.arguments, null, Locale.default
} ?: fe.codes.last()
}
log.info "save failed for $o: $errors"
HttpResponse.badRequest( errors:errors )
}
}
当我调用该操作时,我在我的客户端中得到 400 Bad Request
,但我看到的不是 { errors:[ {..}, {..}, {..} ]
样式 JSON,而是:
{
"message":"Validation Error(s) occurred during save() : Field error in object ... default message [Property [{0}] of class [{1}] cannot be blank]\r\n",
"path":"fullName",
"_links":{"self":{"href":"/person/42","templated":false}}
}
而且 else{}
块从未到达,我没有得到任何进一步的日志。
有什么提示吗?
看来,在 Micronaut 的 GORM 配置中是通过
完成的 compile 'io.micronaut.configuration:micronaut-hibernate-gorm'
默认情况下 failOnError
设置为 true
。这导致 ValidationException
被扔到 save()
而不是填充 o.errors
。
为了解决这个问题,我添加了行
grails.gorm.failOnError: false
我的application.yml
,现在它运行得很好。