java - 处理 @NotBlank 错误 - Spring Boot
问题描述
我正在尝试处理通过@NotBlank
Spring Boot 应用程序中的注释抛出的异常。到目前为止,我的代码处理了MethodArgumentNotValidException
throw by@Size
和@Email
annotations。但是,当我期望@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
?
解决方案
在我停止在控制器中扩展之前,我无法看到错误,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?
)
推荐阅读
- haskell - 在 NixOS 上强制 Haskell Stack 为 1.7.* 版本
- junit - 使用 powerMockito 的 JUnit 测试提供了 NPE
- python - os.stat(path).st_mtime 如何实际获取文件修改时间?
- javascript - 如何“唯一化”一个javascript对象数组?
- python - 烧瓶安全确认注册表未添加新字段
- c - 关闭未使用的管道文件描述符
- c++ - 如何使用 GDB 获取有关异常的更多信息?
- ios - 搜索控制器没有结果(空白页)
- php - 我的 for 循环花费了太多时间
- php - php mysql 只返回一行