java - Spring boot中的枚举绑定异常处理
问题描述
我有一个enum
喜欢:
public enum Age {
THREE("3"),
FIVE("5");
private final String value;
Age(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
和像这样的用户 class
:
public class User {
@NotNull
String name;
Age age;
public User() {
}
public User(@NotNull String name, Age age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Age getAge() {
return age;
}
public void setAge(Age age) {
this.age = age;
}
}
和一个RestController
类似的:
@ExceptionHandler(HttpMessageNotReadableException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseEntity<User> exceptionHandling(HttpMessageNotReadableException exception,
HandlerMethod handlerMethod, WebRequest webRequest) {
logger.error("error:" + exception.getLocalizedMessage());
EnumValidationException ex = (EnumValidationException) exception.getMostSpecificCause();
User user = new User();
user.setName(""); // I want set user's input
user.setAge(Age.FIVE);
return ResponseEntity.ok(user);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<User> exceptionHandling2(MethodArgumentNotValidException exception) {
logger.error("error:" + exception.getLocalizedMessage());
User user = new User();
user.setName(""); // I want set user's input
user.setAge(Age.FIVE);
return ResponseEntity.ok(user);
}
@PostMapping("/user2")
public String setUser2(@Valid @RequestBody User user) {
return "ok";
}
我JSON
喜欢:
{
"name":"Name",
"age":"11"
}
现在我如何处理在字段中HttpMessageNotReadableException
返回的异常?Name
name
response
enum
我应该改成static final String
?
我可以写自定义Annotaion
吗?如何处理它getValue()
?
注意:我使用Hibernate
.
解决方案
如果我理解您的问题,您想打印 的值,而不是名称:在Age
这种情况下,您可以尝试覆盖:toString()
Age
@Override
public String toString() {
return value;
}
如果你想使用 getValue(),你应该阅读 Spring Boot 的文档,尤其是它的底层 JSON API:
推荐阅读
- mongoose - Nestjs e2e 测试与模拟猫鼬模型
- python - 如何在 Django 中计算 Frechet 距离?
- xaml - Vs for Mac 8.1(内部版本 2697)Xaml 预览未加载
- java - 构造域+用户名字符串时如何判断'/'或'\'
- ruby-on-rails - 在 Rails TestCase 中检查正则表达式
- c# - 如何使用 select 和 CopyToDataTable 函数合并数据表中的两列并使其成为单列
- javascript - 当我启动和关闭服务器时,所有查询和突变都不起作用
- node.js - 如何将 req.body 包含对象数组映射到节点 js 中的模型以进行 insertmany
- ios - 用户默认不提供价值
- react-native - 反应导航 headerBackImage 不起作用