返回对象Result
@Data
public class Result<T> implements Serializable {
private int code;
private String msg;
private T data;
private Result(int code, String msg, T data) {
this.code = code;
this.msg = msg;
this.data = data;
}
/**
* 成功返回
* @param data
* @param <T>
* @return
*/
public static <T> Result<T> success(T data){
return new Result<T>(0,"success",data);
}
/**
* 成功返回
* @param <T>
* @return
*/
public static <T> Result<T> success(){
return success(null);
}
/**
* 失败返回
* @param cm
* @param <T>
* @return
*/
public static <T> Result<T> error(CodeMsg cm){
return new Result<T>(cm.getCode(),cm.getMsg(),null);
}
/**
* 失败返回
* @param msg
* @param <T>
* @return
*/
public static <T> Result<T> validationError(String msg){
CodeMsg validationError = CodeMsg.VALIDATION_ERROR;
String format = String.format(validationError.getMsg(), msg);
return new Result<T>(validationError.getCode(),format,null);
}
/**
* 失败返回
* @param msg
* @param <T>
* @return
*/
public static <T> Result<T> commError(String msg){
CodeMsg validationError = CodeMsg.COMM_ERROR;
String format = String.format(validationError.getMsg(), msg);
return new Result<T>(validationError.getCode(),format,null);
}
}
错误提示封装
@Data
public class CodeMsg {
private int code;
private String msg;
/**
* 私有构造器
* @param code
* @param msg
*/
private CodeMsg(int code, String msg) {
this.code = code;
this.msg = msg;
}
/**
* 通用错误返回
*/
public static final CodeMsg SERVER_ERROR = new CodeMsg(60000,"服务器异常!");
public static final CodeMsg VALIDATION_ERROR = new CodeMsg(60001,"参数效验错误:%s!");
public static final CodeMsg BIZ_ERROR = new CodeMsg(60002,"业务异常:%s!");
}
使用
@GetMapping("/applyNo")
public Result applyNo(@RequestParam("applyType") Integer applyType) {
String no = orgApplyService.createNo(applyType);
return Result.success(MapUtil.builder("applyNo", no).map());
}
@PostMapping("save")
public Result save(String applyNo,String commitment) {
service.save(applyNo, commitment);
return Result.success();
}
@PostMapping("save")
public Result save(Param param) {
if(param== null || StringUtils.isBlank(param.getName())){
// 仅仅是举例说明返回哈
return Result.error(CodeMsg.SERVER_ERROR);
}
servicesave(param);
return Result.success();
}
网友评论