【发布时间】:2019-12-23 13:14:37
【问题描述】:
现在我使用 Spring Boot 开发了 REST API。
我尝试验证路径参数并使用这样的自定义消息处理异常。
FooController.java
@Validated
@RestController
@RequiredArgsConstructor
public class FooController {
private final BarService service;
@GetMapping(value = "/test/{id}")
public void invoke(@PathVariable @Digits(integer = 10, fraction = 0, message = "{message}") Long id) {
service.get(id);
...
}
}
ApiExceptionHandler.java
@RestControllerAdvice
@RequiredArgsConstructor
public class ApiExceptionHandler {
@ExceptionHandler(ConstraintViolationException.class)
public ResponseEntity<Object> handleConstraintViolationException(ConstraintViolationException exception) {
Map<String, String> messages = new HashMap<>();
for (ConstraintViolation violation : exception.getConstraintViolations()) {
messages.put("message", violation.getMessage());
}
return new ResponseEntity<>(messages, HttpStatus.BAD_REQUEST);
}
}
ValidationMessages.properties
message={0} must not be more than {integer} digits
当我调用这个 API 超过 10 位时(例如,[GET /test/12345678901])发生 400 错误。
我的预期反应是
{
message : id must not be more than 10 digits
}
但是,实际的反应是
{
message : {0} must not be more than 10 digits
}
所以,我的问题是“为什么不替换验证消息”。
如果这种方法是错误的,那么有什么方法可以得到预期的响应吗?
感谢您阅读我的问题。
附录 使用的 Spring Boot 版本是 2.1.1
【问题讨论】:
标签: java spring spring-boot exception path-variables