future.png
珠玑随笔

联系:

future.png

版权 © 2022 by Hsu

技术: Gatsby

样式: Bulma

许可: CC BY NC SA 4.0

Spring Boot Entity 层的数据验证及错误拦截

2022年01月11日

Hsu

2分钟

背景

Entity 是数据库 ORM 框架表结构的映射,为了保险也可以在 Entity 加验证.

这样就形成了 DTO + Entity 双验证, 具体要不要使用双验证需要看需求.

定义

@Entity
@Table(name = "user")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class User {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @NotBlank(message = "用户名不能为空!")
  @Column(name = "username", nullable = false)
  private String username;

  @NotBlank(message = "密码不能为空!")
  @Column(name = "password", nullable = false)
  private String password;

  @NotBlank(message = "电子邮箱不能为空!")
  @Column(name = "email", nullable = false)
  private String email;
}

异常

如果无法匹配验证规则, 抛出 ConstraintViolationException 异常, 该异常是数组.

@RestControllerAdvice
public class GlobalExceptionHandler {


  @ExceptionHandler(ConstraintViolationException.class)
  public ResponseEntity<?> handleConstraintViolationException(
    ConstraintViolationException ex, WebRequest request) {
    List<String> errors = new ArrayList<>();

    // 获取所有验证错误信息
    ex.getBindingResult().getAllErrors()
                         .forEach(i -> errors.add(i.getDefaultMessage()));

    Map<String, List<String>> result = new HashMap<>();

    result.put("errors", errors);

    ExceptionResponse exceptionResponse = new ExceptionResponse(500, result);

    return new ResponseEntity<>(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR);
  }
}