Spring Kotlin中的非null验证抛出HttpMessageNotReadableException而不是MethodArgumentNotValidException [英] Spring not null validation throwing HttpMessageNotReadableException instead of MethodArgumentNotValidException in kotlin

查看:93
本文介绍了Spring Kotlin中的非null验证抛出HttpMessageNotReadableException而不是MethodArgumentNotValidException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Spring在Kotlin中进行简单的应用程序制作,但是我在验证方面遇到了问题.

I'm making and simple application in Kotlin using Spring but I'm having a problem with the validation.

我有这个实体类:

@Entity
@Table(name = "category")
data class Category(
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        val id: Long?,
        @field:NotNull @field:NotEmpty val name: String)

我的控制器功能如下:

@PostMapping
@ResponseStatus(HttpStatus.CREATED)
fun create(@Valid @RequestBody category: Category): ResponseEntity<Category>

create有一些代码,但是与问题无关,我的问题是请求主体验证.如果我发送带有空名称字段的类别,则会引发MethodArgumentNotValidException异常,但是如果我将null发送到字段name,则会引发异常,引发HttpMessageNotReadableException.有谁知道是否可以将null传递给标有@NotNull的字段,并将MethodArgumentNotValidException也扔到Kotlin中.

create have some code, but it is irrelevant for the question, my problem is with the request body validation. If I send a category with an empty name field, it is thrown a MethodArgumentNotValidException exception, but if I send null to the field name, the exception thrown HttpMessageNotReadableException instead. Does anyone knows if it is possible to make passing null to a field marked with @NotNull to also throw MethodArgumentNotValidException in Kotlin.

推荐答案

因此,您的问题是将name字段指定为不可为空,默认情况下,kotlin的杰克逊模块将对其进行检查并抛出HttpMessageNotReadableException,这是由MissingKotlinParameterException引起的在json映射过程中.如果将name标记为可空,则json映射将通过并通过@Valid进入spring验证阶段,那么我们将获得MethodArgumentNotValidException

So your problem is you specify the name field as not nullable, by default jackson module for kotlin will check it and throw HttpMessageNotReadableException which cause by MissingKotlinParameterException during json mapping process. If you mark name filed as nullable json mapping will passed and get to the spring validation phase with @Valid then we will get MethodArgumentNotValidException

@Entity
@Table(name = "category")
data class Category(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id: Long?,
    @field:NotNull @field:NotEmpty val name: String?)

这篇关于Spring Kotlin中的非null验证抛出HttpMessageNotReadableException而不是MethodArgumentNotValidException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆