簡體   English   中英

驗證失敗時不拋出 MethodArgumentNotValidException

[英]MethodArgumentNotValidException not thrown in case of validation fail

我正在嘗試按照 教程在 Spring REST 中實施驗證。 不過,與教程不同,我的代碼在 Koltin 中。

我的代碼如下 -

實體 class

@Entity
class PodcastEntity(@Id @GeneratedValue(strategy = GenerationType.AUTO) @NotNull
                    var id: Long = 0,
                    @field:NotEmpty(message = "Please provide an author")
                    var author: String,
                    @field:NotEmpty(message = "Please provide a title")
                    var title: String,
                    @field:NotEmpty(message = "Please provide a description")
                    var description: String,
                    @field:NotEmpty(message = "Please provide category one")
                    var categoryOne: String,
                    @field:NotEmpty(message = "Please provide category two")
                    var categoryTwo: String,
                    var filePath: String = "")

我的 post 方法在controller中是這樣的 -

@PostMapping("details")
fun addPodcast(@Valid @RequestBody podcastEntity: PodcastEntity) {
    podcastService.addPodcast(podcastEntity)
}

我在 postman 中的 POST 請求是這樣的——

{
    "author" : "me 3",
    "title" : "File three",
    "description" : "this is a test desc"
}

由於缺少categoryOnecategoryTwo並且我沒有自己處理異常,我的控制台應該根據教程顯示MethodArgumentNotValidException 但是,我沒有得到這樣的例外。 我得到的是一個HttpMessageNotReadableException異常-

Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Instantiation of [simple type, class com.krtkush.test.entities.PodcastEntity] value failed for JSON property categoryOne due to missing (therefore NULL) value for creator parameter categoryOne which is a non-nullable type; nested exception is com.fasterxml.jackson.module.kotlin.MissingKotlinParameterException: Instantiation of [simple type, class com.krtkush.test.entities.PodcastEntity] value failed for JSON property categoryOne due to missing (therefore NULL) value for creator parameter categoryOne which is a non-nullable type  at [Source: (PushbackInputStream); line: 5, column: 1] (through reference chain: com.krtkush.test.entities.PodcastEntity["categoryOne"])]

我無法理解我要去哪里錯了。 請幫忙?

您可以通過提供HttpMessageNotReadableException處理程序然后檢查主要原因是否是MissingKotlinParameterException來處理此問題。

之后,您可以提供自定義驗證錯誤。

    @ExceptionHandler
    override fun handleMessageNotReadableException(
        exception: HttpMessageNotReadableException,
        request: NativeWebRequest
    ): ResponseEntity<Problem> {
        // workaround
        val cause = exception.cause
        if (cause is MissingKotlinParameterException) {
            val violations = setOf(createMissingKotlinParameterViolation(cause))
            return newConstraintViolationProblem(exception, violations, request)
        }
        return create(Status.BAD_REQUEST, UnableToReadInputMessageProblem(), request)
    }

    private fun createMissingKotlinParameterViolation(cause: MissingKotlinParameterException): Violation {
        val name = cause.path.fold("") { jsonPath, ref ->
            val suffix = when {
                ref.index > -1 -> "[${ref.index}]"
                else -> ".${ref.fieldName}"
            }
            (jsonPath + suffix).removePrefix(".")
        }
        return Violation(name, "must not be null")
    }

這樣你就可以得到很好的 output 並帶有適當的約束錯誤。

您可以嘗試直接為MissingKotlinParameterException聲明@ExceptionHandler

基於問題Spring 而不是 null 驗證的答案在 kotlin 中拋出 HttpMessageNotReadableException 而不是 MethodArgumentNotValidException

按照 Damian 在他的答案中的 SO 鏈接,我發現第一個答案非常有用且更合適。 我修改了@Entitiy class,使必填字段可以為空( ? ),如下所示 -

@Entity
class PodcastEntity(@Id @GeneratedValue(strategy = GenerationType.AUTO)
                    var id: Long = 0,
                    @field:NotEmpty(message = "Please provide an author")
                    var author: String?,
                    @field:NotEmpty(message = "Please provide a title")
                    var title: String?,
                    @field:NotEmpty(message = "Please provide a description")
                    var description: String?,
                    @field:NotEmpty(message = "Please provide category one")
                    var categoryOne: String?,
                    @field:NotEmpty(message = "Please provide category two")
                    var categoryTwo: String?,
                    var filePath: String = "")

這確保代碼在所有三種情況下都拋出MethodArgumentNotValidException - 1. 空參數 2. null參數 3. 缺少參數

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM