springboot通用返回类与@Validated参数校验

通用返回类

1. Icode接口

public interface ICode {

    long getCode();

    String getMessage();
}

2. ResultCode枚举

@AllArgsConstructor
public enum ResultCode implements ICode{

    SUCCESS(200, "操作成功"),

    ERROR(500, "操作失败"),

    VALIDATE_FAILED(400, "参数检验失败"),

    UNAUTHORIZED(401, "未经授权"),

    FORBIDDEN(403, "没有权限"),

    BUSINESS_ERROR(590, "业务异常");

    private long code;

    private String message;

    @Override
    public long getCode() {
        return code;
    }

    @Override
    public String getMessage() {
        return message;
    }
}

3. CommonResult类

@Getter
@Setter
@NoArgsConstructor
public class CommonResult<T> {
    private long code;
    private String message;
    private T data;

    protected CommonResult(long code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    /**
     * 成功返回结果
     * @param data 获取的数据
     */
    public static <T> CommonResult<T> success(T data) {
        return commonResult(ResultCode.SUCCESS , data);
    }
    /**
     * 成功返回结果
     * @param data 获取的数据
     * @param  message 提示信息
     */
    public static <T> CommonResult<T> success(String message , T data) {
        return new CommonResult<T>(ResultCode.SUCCESS.getCode(), message, data);
    }
    /**
     * 失败返回结果
     */
    public static <T> CommonResult<T> error() {
        return commonResult(ResultCode.ERROR , null);
    }
    /**
     * 失败返回结果
     * @param message 提示信息
     */
    public static <T> CommonResult<T> error(String message) {
        return new CommonResult<T>(ResultCode.ERROR.getCode(), message, null);
    }
    /**
     * 参数验证失败返回结果
     */
    public static <T> CommonResult<T> validateFailed() {
        return commonResult(ResultCode.VALIDATE_FAILED , null);
    }
    /**
     * 参数验证失败返回结果
     * @param message 提示信息
     */
    public static <T> CommonResult<T> validateFailed(String message) {
        return new CommonResult<T>(ResultCode.VALIDATE_FAILED.getCode(), message, null);
    }
    /**
     * 未登录返回结果
     */
    public static <T> CommonResult<T> unauthorized(T data) {
        return commonResult(ResultCode.UNAUTHORIZED , data);
    }
    /**
     * 未授权返回结果
     */
    public static <T> CommonResult<T> forbidden(T data) {
        return commonResult(ResultCode.FORBIDDEN , data);
    }
    /**
     * 业务异常返回结果
     * @param message 提示信息
     */
    public static <T> CommonResult<T> bizError(String message) {
        return new CommonResult<T>(ResultCode.BUSINESS_ERROR.getCode(), message, null);
    }

    /**
     * 通用返回结果方法
     * @param iCode
     * @return
     */
    private static <T> CommonResult<T> commonResult(ICode iCode , T data) {
        return new CommonResult<T>(iCode.getCode(), iCode.getMessage(), data);
    }
}

参数校验

1. ValidateCodeException类

public class ValidateCodeException extends AuthenticationException {

    private static final long serialVersionUID = 1L;

    public ValidateCodeException(String message) {
        super(message);
    }
}

2. WebExceptionHandler类

@Slf4j
@RestControllerAdvice
public class WebExceptionHandler {

    @ExceptionHandler(ValidateCodeException.class)
    public CommonResult handleValidateCodeException(ValidateCodeException e) {
        log.error(e.getMessage(), e);
        return CommonResult.error(e.getMessage());
    }

    /**
     * @param exception
     * @return
     */
    @ExceptionHandler({ConstraintViolationException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public CommonResult constraintViolationExceptionHandler(ConstraintViolationException exception) {
        StringBuilder messagesb = new StringBuilder();
        String[] messages = exception.getMessage().split(", ");
        for (String message : messages) {
            messagesb.append(message.substring(message.indexOf(":")+2));
            messagesb.append(", ");
        }
        String message = messagesb.toString();
        message = message.substring(0, messagesb.toString().lastIndexOf(", "));
        log.warn(message);
        return CommonResult.validateFailed(message);
    }
}

3. TestValidatedController

@RestController
//非对象接收的参数 在类上需要添加该注解
@Validated
@Slf4j
public class TestValidatedController {
    
    @GetMapping("/testParameter")
    public CommonResult testParameter(
            @NotBlank(message = "testParameter1不能为空")
            String testParameter1,
            @NotBlank(message = "testParameter2不能为空")
            String testParameter2){
        return CommonResult.success(testParameter1+","+testParameter2);
    }
}

测试

输入 http://localhost:8080/testParameter
结果 {“code”:400,“message”:“testParameter2不能为空, testParameter1不能为空”,“data”:null}

输入 http://localhost:8080/testParameter?testParameter1=test1
结果 {“code”:400,“message”:“testParameter2不能为空”,“data”:null}

输入 http://localhost:8080/testParameter?testParameter1=test1&testParameter2=test2
结果 {“code”:200,“message”:“操作成功”,“data”:“test1,test2”}

你可能感兴趣的:(springboot通用返回类与@Validated参数校验)