【问题标题】:bean validation working but empty message on Kotlinbean验证工作但Kotlin上的空消息
【发布时间】:2021-03-23 02:32:40
【问题描述】:

我正在尝试让 Kotlin 在 spring-webflux 项目中使用 bean 验证。
请求似乎被正确验证,但响应正文的消息是空的,因此很难知道错误的原因。

很想从响应中获取默认验证消息?

控制器:

class SomeController {
    @PostMapping("/foo")
    fun foo(@Valid @RequestBody body: FooRequest): Mono<FooRequest> {
        return Mono.just(body)
    }
}

请求:

data class FooRequest(
    @field:Min(0)
    val bar: Int
)

使用请求"{\"bar\":-1}"调用该api的响应是

{
  "timestamp": "2021-03-23T02:18:49.368+00:00",
  "path": "/api/v1/foo",
  "status": 400,
  "error": "Bad Request",
  "message": "",
  "requestId": "d1739c79-6"
}

【问题讨论】:

  • 我很好奇您是否在注释中添加了自定义消息,它会通过吗?如果确实如此,则证明注释是问题所在,否则是其他问题。
  • 刚刚遇到了同样的问题。
  • 检查你的日志你在日志中有正确的消息
  • @DCTID 即使我设置了自定义消息,响应也没有显示。

标签: spring-boot kotlin bean-validation


【解决方案1】:

所以看完这篇https://www.baeldung.com/spring-boot-bean-validation

我最终添加了一个这样的异常处理程序:

@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseEntity<Map<String,String>> handleMethodArgumentNotValidException(MethodArgumentNotValidException exception) {
    Map<String, String> errors = new HashMap<>();
    exception.getBindingResult().getAllErrors().forEach((error) -> {
        String fieldName = ((FieldError) error).getField();
        String errorMessage = error.getDefaultMessage();
        errors.put(fieldName, errorMessage);
    });
    return ResponseEntity
            .status(HttpStatus.BAD_REQUEST)
            .body(errors);
}

【讨论】:

    猜你喜欢
    • 2016-06-21
    • 2019-02-25
    • 2011-12-24
    • 2011-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多