如何使用JSR303驗證及自定義訊息統一處理

zhangjianshan007發表於2020-12-10

1.引入pom

        <!--validation驗證-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>

2.需要驗證的實體型別加對應的註解(以非空判斷為例)

    @NotBlank(message = "單位名稱不能為空")
    private String orgName;

3.Controller對應方法裡新增@Validated

  public CommonResult createArmyOrg(@Validated @RequestBody ArmyOrg createArmyOrg) {
        return armyOrgService.createArmyOrg(createArmyOrg);
    }

4.驗證結果,顯示比較亂

在這裡插入圖片描述

5.新增統一異常返回類ApiError

/**
 * @author zhangjianshan on 2020-10-23
 */
@Data
public class ApiError {

    private Integer status = 400;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime timestamp;
    private String message;

    private ApiError() {
        timestamp = LocalDateTime.now();
    }

    public static ApiError error(String message) {
        ApiError apiError = new ApiError();
        apiError.setMessage(message);
        return apiError;
    }

    public static ApiError error(Integer status, String message) {
        ApiError apiError = new ApiError();
        apiError.setStatus(status);
        apiError.setMessage(message);
        return apiError;
    }
}

6.新增全域性異常處理ExceptionHandle

/**
 * @author zhangjianshan on 2020-12-08
 */
@RestControllerAdvice
public class ExceptionHandle {


    /**
     * Validated
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ApiError> exceptionHandler(MethodArgumentNotValidException e) {
        return buildResponseEntity(ApiError.error(e.getBindingResult().getFieldError().getDefaultMessage()));
    }
    /**
     * 重複
     *
     * @param e
     * @return
     */
    @ExceptionHandler(RepetitionException.class)
    public ResponseEntity<ApiError> repetitionException(RepetitionException e) {
        return buildResponseEntity(ApiError.error(e.getMessage()));
    }

    /**
     * 統一返回
     */
    private ResponseEntity<ApiError> buildResponseEntity(ApiError apiError) {
        return new ResponseEntity<>(apiError, HttpStatus.valueOf(apiError.getStatus()));
    }
}

7.再次驗證結果

在這裡插入圖片描述

相關文章