首页 > 解决方案 > 处理 @NotBlank 错误 - Spring Boot

问题描述

我正在尝试处理通过@NotBlankSpring Boot 应用程序中的注释抛出的异常。到目前为止,我的代码处理了MethodArgumentNotValidExceptionthrow by@Size@Emailannotations。但是,当我期望@NotBlank返回一条消息时,我得到一个空的响应正文,向我表明正在引发不同类型的异常,但我不清楚是哪一个:

查看正在验证的模型:

import javax.validation.constraints.Email
import javax.validation.constraints.NotBlank
import javax.validation.constraints.Size

data class SignupDto(
    @field:NotBlank(message = "Email Address is mandatory.")
    @field:Email(message = "Email Address is invalid.")
    val emailAddress: String,

    @field:NotBlank(message = "First Name is mandatory.")
    @field:Size(min = 2, max = 255, message = "First Name must be between 2 and 255 characters.")
    val firstName: String,

    @field:Size(min = 2, max = 255, message = "Last Name must be between 2 and 255 characters.")
    val lastName: String? = null,

    @field:NotBlank(message = "Password is mandatory")
    val password: String
)

和处理程序

package com.travisalexandersmith.runjamaicaapi.auth

import com.travisalexandersmith.runjamaicaapi.auth.exceptions.EmailAddressTakenException
import com.travisalexandersmith.runjamaicaapi.global.responses.ErrorMessage
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.MethodArgumentNotValidException
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.context.request.WebRequest
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler

@ControllerAdvice
class AuthControllerAdvisor : ResponseEntityExceptionHandler() {
    private val logger: Logger = LoggerFactory.getLogger("AuthControllerAdvisor")

    @ExceptionHandler(EmailAddressTakenException::class)
    fun handleEmailAddressTakenExceptions(
        exception: EmailAddressTakenException,
        request: WebRequest
    ): ResponseEntity<ErrorMessage> {
        logger.info(exception.message)
        val errorMessage = ErrorMessage(exception.message)
        return ResponseEntity<ErrorMessage>(errorMessage, HttpStatus.CONFLICT)
    }

    override fun handleMethodArgumentNotValid(
        ex: MethodArgumentNotValidException,
        headers: HttpHeaders,
        status: HttpStatus,
        request: WebRequest
    ): ResponseEntity<Any> {
        val fieldErrors = ex.bindingResult.fieldErrors.map { it.defaultMessage }
        return ResponseEntity<Any>(ErrorMessage(error = "Invalid request body.", details = fieldErrors), HttpStatus.BAD_REQUEST)
    }
}

这是关联的控制器:

package com.travisalexandersmith.runjamaicaapi.auth

import com.travisalexandersmith.runjamaicaapi.auth.dto.SignupDto
import com.travisalexandersmith.runjamaicaapi.auth.responses.AuthResponse
import com.travisalexandersmith.runjamaicaapi.auth.services.AuthService
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpStatus
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*
import javax.validation.Valid


@RestController
@RequestMapping("auth")
@Validated
class AuthController @Autowired constructor(val authService: AuthService) {
    private val logger: Logger = LoggerFactory.getLogger("AuthController")

    @PostMapping("/signup")
    @ResponseStatus(HttpStatus.CREATED)
    fun signup(@Valid @RequestBody signupDto: SignupDto): AuthResponse {
        logger.info("Request to signup for user with email address ${signupDto.emailAddress}")
        return authService.signup(signupDto)
    }
}

我应该在此处添加什么来管理异常@NotBlank

标签: javaspring-bootkotlin

解决方案


在我停止在控制器中扩展之前,我无法看到错误,ResponseEntityExceptionHandler我看到这个错误来自DefaultHandlerExceptionResolver

 com.fasterxml.jackson.module.kotlin.MissingKotlinParameterException: Instantiation of [simple type, class com.travisalexandersmith.runjamaicaapi.auth.dto.SignupDto] value failed for JSON property emailAddress due to missing (therefore NULL) value for creator parameter emailAddress which is a non-nullable type

问题是SignupDto必须将 中的字段标记为可为空,否则当它们丢失时将引发此异常:

data class SignupDto(
    @field:NotBlank(message = "Email Address is mandatory.")
    @field:Email(message = "Email Address is invalid.")
    val emailAddress: String?,

    @field:NotBlank(message = "First Name is mandatory.")
    @field:Size(min = 2, max = 255, message = "First Name must be between 2 and 255 characters.")
    val firstName: String?,

    @field:Size(min = 2, max = 255, message = "Last Name must be between 2 and 255 characters.")
    val lastName: String? = null,

    @field:NotBlank(message = "Password is mandatory")
    val password: String?
)

推荐阅读