繁体   English   中英

Spring 未显示引导验证消息

[英]Spring Boot validation message not shown

我有一个 Spring 启动应用程序(版本 2.4.5)作为一个 Kotlin 项目。 现在,当我输入无效的内容时,我会收到一条错误消息,但不会收到我在注释中设置的错误消息。

Controller

  @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
        }
    }

数据 class

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",
}

如果我设置属性,它会向我显示正确的属性,但我不想拥有所有辅助信息,我只想 output 消息

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

好的,我终于找到了解决方案。 我创建了一个侦听 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

@Yunz我认为“错误”属性已添加到您的响应中,因为您设置了server.error.include-binding-errors=always您可以尝试将其设置为never或不定义此属性并依赖默认值( never )。

从2.3版本开始需要设置server.error.include-message=always ,Spring Boot在响应中隐藏message字段,避免泄露敏感信息; 我们可以使用这个属性和一个 always 值来启用它

有关详细信息,请查看spring 引导文档

请使用相应的ExceptionHandler创建以下ControllerAdvice 应该是这样的:

@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Map<String, String> handleValidationExceptions(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });
        return errors;
    }
}

在最近的 Spring Boot 版本中,错误消息的发送被禁用,现在需要手动实现,如上所示。

参考: https://www.baeldung.com/spring-boot-bean-validation#the-exceptionhandler-annotation

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM