springboot2 统一全局异常处理 参数校验 Validation

2023-01-28 17:55:32

Validation 常用注解

@NotBlank 字符串不能为空

@NotNull 对象不能为空

@NotEmpty 集合不能为空

validation 注解 message动态字符

@Length(max = 100, message = "广告主uid最多查询{max}条")

示例

/**
 * 阙值档位
 */
@NotNull(message = "阙值档位不能为空")
@Min(value = 1, message = "档位最低不能小于{value}")
@Max(value = 100000000, message = "档位最大不能大于{value}")
private Long level;

/**
 * 操作人邮箱
 */
@NotBlank(message = "操作人邮箱不能为空")
@Length(max = 50, message = "操作人邮箱最多{max}个字符")
@Email(message = "邮箱格式不正确")
private String operatorMail;

/**
 * 本金 单位:元
 */
@NotNull(message = "充值本金不能为空")
@DecimalMin(value = "0", message = "充值本金不能小于0", inclusive = false)
@Digits(integer = 7, fraction = 2, message = "充值本金最大{integer}位整数,最小{fraction}位小数")
private BigDecimal principal;

/**
 * 返点 单位:元
 */
@DecimalMin(value = "0", message = "充值返点不能为负数")
@Digits(integer = 7, fraction = 2, message = "充值返点最大{integer}位整数,最小{fraction}位小数")
private BigDecimal rebate;

/**
* 手机号
 */
@NotBlank(message = "手机号不能为空")
@Pattern(regexp = "[1][0-9]{10}", message = "手机号码格式不正确")
private String mobile;


/**
 * 计划id集合  (对象中的对象或集合校验需加上@Valid注解)
 */
@Valid
@NotEmpty(message = "计划id集合不能为空")
private List<OcpxRechargeAdplanDTO> adPlans;

Spring Validation 参数校验

SpringBoot 如何进行参数校验

springboot-如何设计优秀的后端接口

spring-boot 对参数进行优雅的校验

Spring Boot 优雅地实现接口参数校验

Spring Validation最佳实践及其实现原理,参数校验没那么简单!

hibernate-validator 各校验注解详细解释

Java 是如何优雅地实现接口数据校验的?

统一参数校验validator 从使用到走向自定义参数校验

自定义参数检验 枚举类型校验

利用Hibernate Validation对Bean中的属性Bean的属性进行验证

参数校验封装工具类

返回参数统一包装

Spring Boot 无侵入式 实现 API 接口统一 JSON 格式返回

如何设计 API 接口,实现统一格式返回?

返回参数错误码定义:

阿里云api 返回参数定义实例

百度云api 返回参数定义实例

全局异常处理

系统全局统一异常处理

springboot全局异常处理,实体类@Validated注解校验,分组校验实现示例

SpringBoot全局异常处理

为什么不建议用try catch处理异常?

全局统一异常处理实现类

/**
 * 自定义全局异常处理类
 *
 * @author zhaoyang10
 * @date 2019/12/23
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = BusinessException.class)
    public ResponseEntity<ExceptionResult> businessException(Exception e) {
        logger.info("BusinessException", e);
        BusinessException businessException = (BusinessException) e;
        ExceptionResult result = new ExceptionResult(businessException.getCode(), businessException.getMessage());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @ExceptionHandler(value = FmsHystrixBadRequestException.class)
    public ResponseEntity<ExceptionResult> fmsHystrixBadRequestException(Exception e) {
        logger.error("FmsHystrixBadRequestException", e);
        FmsHystrixBadRequestException exception = (FmsHystrixBadRequestException) e;
        ExceptionResult result = new ExceptionResult(ErrorCode.FEIGN_SERVICE_ERROR, exception.getMessage());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<ExceptionResult> exception(Exception e) {
        logger.error("Exception", e);
        ExceptionResult result = new ExceptionResult(ErrorCode.API_SERVICE_ERROR.getCode(), "系统错误", e.getMessage());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseEntity<ExceptionResult> methodArgumentNotValidException(MethodArgumentNotValidException e) {
        logger.info("MethodArgumentNotValidException", e);
        List<String> errorInformation = e.getBindingResult().getAllErrors()
                .stream()
                .map(ObjectError::getDefaultMessage)
                .collect(Collectors.toList());
        ExceptionResult result = new ExceptionResult(ErrorCode.API_PARAM_NOT_LEGAL, errorInformation.toString());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @ExceptionHandler(value = ConstraintViolationException.class)
    public ResponseEntity<ExceptionResult> constraintViolationException(ConstraintViolationException e) {
        logger.info("ConstraintViolationException", e);
        Set<ConstraintViolation<?>> cves = e.getConstraintViolations();
        StringBuilder errorMsg = new StringBuilder();
        cves.forEach(ex -> errorMsg.append(ex.getMessage()));
        ExceptionResult result = new ExceptionResult(ErrorCode.API_PARAM_NOT_LEGAL, errorMsg.toString());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @ExceptionHandler(BindException.class)
    public ResponseEntity<ExceptionResult> bindException(BindException e) {
        logger.info("BindException", e);
        FieldError fieldError = e.getBindingResult().getFieldError();
        String message = "";
        if (fieldError != null) {
            message = fieldError.getDefaultMessage();
        }
        ExceptionResult result = new ExceptionResult(ErrorCode.API_PARAM_NOT_LEGAL, message);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 公共代码公共异常抛出
     *
     * @param e e
     * @return ResponseEntity
     * @author zhaoyang10
     */
    @ExceptionHandler(value = CommonException.class)
    public ResponseEntity<ExceptionResult> commonException(Exception e) {
        logger.info("CommonException", e);
        CommonException commonException = (CommonException) e;
        ExceptionResult result = new ExceptionResult(commonException.getCode(), commonException.getMessage());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

}
  • 作者:zhaoyang10
  • 原文链接:https://blog.csdn.net/fzy629442466/article/details/85718551
    更新时间:2023-01-28 17:55:32