spring启动验证消息未显示

ie3xauqp  于 2021-07-12  发布在  Java
关注(0)|答案(2)|浏览(354)

我有一个spring启动应用程序(版本为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
        }
    }

数据类

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?
)

我的回答应该是message=“name is empty”

{
  "timestamp": "2021-04-22T19:47:08.194+00:00",
  "status": 400,
  "error": "Bad Request",
  "message": "Validation failed for object='data'. Error count: 1",
}

如果我设置了属性,它会显示正确的属性,但我不想拥有所有的边信息,我只想输出消息

server.error.include-binding-errors=always

结果:

{
  "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"
}
e4yzc0pl

e4yzc0pl1#

@yunz我认为自从你设置了 server.error.include-binding-errors=always 你能把它调成 never 或者不定义此属性并依赖于默认值(即 never ).
你需要设置 server.error.include-message=always 从2.3版开始,spring boot在响应中隐藏消息字段,避免敏感信息泄露;我们可以将此属性与always值一起使用以启用它
有关详细信息,请参阅spring boot文档:

ar7v8xwq

ar7v8xwq2#

好吧,我终于找到了解决办法。我创建了一个全局异常处理程序,用于侦听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
    }

}

资料来源:https://www.baeldung.com/spring-boot-bean-validation

相关问题