首页 > 解决方案 > 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返回的异常?Namenameresponse

enum我应该改成static final String?

我可以写自定义Annotaion吗?如何处理它getValue()

注意:我使用Hibernate.

标签: javahibernatespring-bootenumsexception-handling

解决方案


如果我理解您的问题,您想打印 的值,而不是名称:在Age这种情况下,您可以尝试覆盖:toString()Age

@Override
public String toString() {
  return value;
}

如果你想使用 getValue(),你应该阅读 Spring Boot 的文档,尤其是它的底层 JSON API:


推荐阅读