Yun*_*unz 6 java validation spring kotlin spring-boot
我有一个 Spring Boot 应用程序(版本 2.4.5)作为 Kotlin 项目。现在,当我输入无效内容时,我会收到一条错误消息,但不是我在注释中设置的错误消息。
控制器
@PostMapping(value = ["/seatMap/save"])
fun addSeatPlan(@RequestPart @Valid data: DSeatMap, @RequestPart image: MultipartFile?, auth: AuthenticationToken) {
try {
if (data.uuid == null) {
seatService.addSeatMap(auth.organisation!!, data, image)
} else {
seatService.updateSeatMap(data, auth.organisation!!, image)
}
} catch (e: UnauthorizedException) {
throw e
}
}
Run Code Online (Sandbox Code Playgroud)
数据类
import java.util.*
import javax.validation.constraints.NotEmpty
data class DSeatMap(
var uuid: UUID?,
@field:NotEmpty(message = "name is empty")
val name: String,
var data: String,
val quantity: Int,
var settings: DSettings?
)
Run Code Online (Sandbox Code Playgroud)
我的回复,这里应该是消息=“名称为空”
{
"timestamp": "2021-04-22T19:47:08.194+00:00",
"status": 400,
"error": "Bad Request",
"message": "Validation failed for object='data'. Error count: 1",
}
Run Code Online (Sandbox Code Playgroud)
如果我设置该属性,它会显示正确的属性,但我不想获得所有辅助信息,我只想输出消息
server.error.include-binding-errors=always
Run Code Online (Sandbox Code Playgroud)
结果:
{
"timestamp": "2021-04-22T19:56:30.058+00:00",
"status": 400,
"error": "Bad Request",
"message": "Validation failed for object='data'. Error count: 1",
"errors": [
{
"codes": [
"NotEmpty.data.name",
"NotEmpty.name",
"NotEmpty.java.lang.String",
"NotEmpty"
],
"arguments": [
{
"codes": [
"data.name",
"name"
],
"arguments": null,
"defaultMessage": "name",
"code": "name"
}
],
"defaultMessage": "name is empty",
"objectName": "data",
"field": "name",
"rejectedValue": "",
"bindingFailure": false,
"code": "NotEmpty"
}
],
"path": "/api/dashboard/seatMap/save"
}
Run Code Online (Sandbox Code Playgroud)
好吧,我终于找到了解决方案。我创建了一个监听 MethodArgumentNotValidException 的全局异常处理程序。之后,我操作该消息并设置我之前在注释中设置的验证消息
@RestControllerAdvice
class ExceptionControllerAdvice {
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException::class)
fun handleValidationExceptions(ex: MethodArgumentNotValidException): Map<String, String?>? {
val errors: MutableMap<String, String?> = HashMap()
ex.bindingResult.allErrors.forEach { error: ObjectError ->
val fieldName = (error as FieldError).field
val errorMessage = error.getDefaultMessage()
errors[fieldName] = errorMessage
}
return errors
}
}
Run Code Online (Sandbox Code Playgroud)
来源: https: //www.baeldung.com/spring-boot-bean-validation
@Yunz我认为“错误”属性会添加到您的响应中,因为您设置了
server.error.include-binding-errors=always您可以尝试将其设置为never或不定义此属性并依赖默认值(即never)。
需要设置server.error.include-message=always从2.3版本开始,Spring Boot隐藏响应中的message字段,避免泄露敏感信息;我们可以使用带有always值的这个属性来启用它
有关详细信息,请查看Spring Boot 文档:
| 归档时间: |
|
| 查看次数: |
10585 次 |
| 最近记录: |