优化Result
This commit is contained in:
@@ -1,5 +1,7 @@
|
||||
package com.mir4updater.backend;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.mybatis.spring.annotation.MapperScan;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
@@ -12,9 +14,12 @@ import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
@MapperScan({"com.mir4updater.backend.mapper", "com.mir4updater.backend.api"})
|
||||
@EnableCaching
|
||||
public class Application {
|
||||
public static Logger logger = LogManager.getLogger(Application.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Application.class, args);
|
||||
logger.info("run dir is " + System.getProperty("user.dir"));
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ public class HelloController {
|
||||
|
||||
@GetMapping("/")
|
||||
public Result getMethodName() {
|
||||
return Result.ok();
|
||||
return Result.success();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -32,12 +32,12 @@ public class CheckUpdateController {
|
||||
});
|
||||
if (apkInfoOptional.isPresent()) {
|
||||
if (versionCode == 0) {
|
||||
return Result.ok().data("apkInfo", apkInfoOptional.get());
|
||||
return Result.success().setData(apkInfoOptional.get());
|
||||
} else {
|
||||
if (apkInfoOptional.get().getVersionCode() > versionCode) {
|
||||
return Result.ok().data("apkInfo", apkInfoOptional.get());
|
||||
return Result.success().setData(apkInfoOptional.get());
|
||||
} else {
|
||||
return Result.ok().message("没有更新");
|
||||
return Result.success().setMessage("没有更新");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -49,6 +49,6 @@ public class CheckUpdateController {
|
||||
@GetMapping("/android/get_all")
|
||||
public Result getAll() {
|
||||
List<ApkInfo> apkInfoList = apkInfoService.getAll();
|
||||
return Result.ok().data("apkInfo", apkInfoList);
|
||||
return Result.success().setData(apkInfoList);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,6 +59,8 @@ public class UploadApkController {
|
||||
//1.接收上传的应用,写入到硬盘
|
||||
String originalFilename = multipartFile.getOriginalFilename();
|
||||
File file = new File(dirPath + File.separator + originalFilename);
|
||||
logger.info("file path = " + file.getAbsolutePath());
|
||||
|
||||
try {
|
||||
multipartFile.transferTo(file);
|
||||
} catch (FileUploadException e) {
|
||||
@@ -66,7 +68,7 @@ public class UploadApkController {
|
||||
}
|
||||
|
||||
if (!isAPK(file) && !isXAPK(file)) {
|
||||
return Result.error().message("请上传apk或xapk文件");
|
||||
return Result.error().setMessage("请上传apk或xapk文件");
|
||||
}
|
||||
String md5 = HashUtils.getFileMD5(file);
|
||||
logger.info("file md5 = " + md5);
|
||||
@@ -116,10 +118,12 @@ public class UploadApkController {
|
||||
} catch (DataIntegrityViolationException e) {
|
||||
e.printStackTrace();
|
||||
logger.info(e.getMessage());
|
||||
return Result.error().message("apk文件无效");
|
||||
File file1 = new File(file.getAbsolutePath());
|
||||
logger.info("delete:" + file1.delete());
|
||||
return Result.error().setMessage("apk文件无效");
|
||||
}
|
||||
|
||||
return Result.ok().message("上传成功");
|
||||
return Result.success().setMessage("上传成功");
|
||||
} else if (isXAPK(file)) {
|
||||
logger.info("file type is xapk");
|
||||
try (ZipFile zipFile = new ZipFile(file)) {
|
||||
@@ -171,28 +175,28 @@ public class UploadApkController {
|
||||
logger.info(e.getMessage());
|
||||
// 手动回滚事务
|
||||
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
|
||||
return Result.error().message("xapk文件重复");
|
||||
return Result.error().setMessage("xapk文件重复");
|
||||
}
|
||||
|
||||
return Result.ok().message("上传成功");
|
||||
return Result.success().setMessage("上传成功");
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
System.err.println("读取文件失败: " + manifestZipEntry.getName());
|
||||
return Result.error().message("读取文件失败");
|
||||
return Result.error().setMessage("读取文件失败");
|
||||
}
|
||||
} else {
|
||||
return Result.error().message("读取xapk配置失败");
|
||||
return Result.error().setMessage("读取xapk配置失败");
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
System.err.println("打开ZIP文件失败: " + e.getMessage());
|
||||
return Result.error().message("打开ZIP文件失败");
|
||||
return Result.error().setMessage("打开ZIP文件失败");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return Result.error().message("文件为空");
|
||||
return Result.error().setMessage("文件为空");
|
||||
}
|
||||
return Result.error().message("未知错误");
|
||||
return Result.error().setMessage("未知错误");
|
||||
}
|
||||
|
||||
// 判断是否为APK
|
||||
|
||||
@@ -39,17 +39,17 @@ public class UploadPakFileController {
|
||||
public Result uploadPakFile(@Valid @ModelAttribute PakFileInfo pakFileInfo) throws Exception {
|
||||
String jsonUuid = pakFileInfo.json_uuid();
|
||||
if (!Boolean.TRUE.equals(stringRedisTemplate.hasKey("data:" + Collections.singletonMap("uuid", jsonUuid)))) {
|
||||
return Result.error().message("json_uuid不存在");
|
||||
return Result.error().setMessage("json_uuid不存在");
|
||||
}
|
||||
InputStream inputStream = pakFileInfo.file().getInputStream();
|
||||
String sha1 = HashUtils.calculateSHA1(inputStream);
|
||||
logger.info("origin_sha1 = " + pakFileInfo.sha1());
|
||||
logger.info("sha1 = " + sha1);
|
||||
if (!sha1.equalsIgnoreCase(pakFileInfo.sha1())) {
|
||||
return Result.error().message("sha1不匹配");
|
||||
return Result.error().setMessage("sha1不匹配");
|
||||
}
|
||||
|
||||
return Result.ok();
|
||||
return Result.success();
|
||||
}
|
||||
|
||||
@PostMapping("/android/upload_pak_file_old")
|
||||
@@ -64,10 +64,10 @@ public class UploadPakFileController {
|
||||
logger.info("origin_sha1 = " + origin_sha1);
|
||||
logger.info("sha1 = " + sha1);
|
||||
if (!sha1.equalsIgnoreCase(origin_sha1)) {
|
||||
return Result.error().message("sha1不匹配");
|
||||
return Result.error().setMessage("sha1不匹配");
|
||||
}
|
||||
|
||||
return Result.ok();
|
||||
return Result.success();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -23,6 +23,6 @@ public class UploadPakInfoController {
|
||||
public Result createData(@Valid @RequestBody PakInfoJsonRequest request) {
|
||||
String id = pakInfoService.processData(request);
|
||||
|
||||
return Result.ok().data(Collections.singletonMap("uuid", id));
|
||||
return Result.success().setData(Collections.singletonMap("uuid", id));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
package com.mir4updater.backend.handler;
|
||||
|
||||
import com.mir4updater.backend.result.Result;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.validation.FieldError;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.MissingServletRequestParameterException;
|
||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.servlet.resource.NoResourceFoundException;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 统一异常处理
|
||||
*
|
||||
* @author 爷爷的茶七里香
|
||||
* @date 2022/05/30 ControllerAdvice注解的含义是当异常抛到controller层时会拦截下来
|
||||
*/
|
||||
@ControllerAdvice
|
||||
public class GlobalExceptionHandler {
|
||||
|
||||
/**
|
||||
* 使用ExceptionHandler注解声明处理Exception异常
|
||||
*
|
||||
* @param e e
|
||||
* @return {@link Result}
|
||||
*/
|
||||
@ResponseBody
|
||||
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
@ExceptionHandler(Exception.class)
|
||||
public Result handlerException(Exception e) {
|
||||
// 控制台打印异常
|
||||
e.printStackTrace();
|
||||
// 返回错误格式信息
|
||||
return Result.error().setMessage(e.getMessage());
|
||||
}
|
||||
|
||||
@ResponseBody
|
||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||
@ExceptionHandler(MissingServletRequestParameterException.class)
|
||||
public Result handlerMissingServletRequestParameterException(MissingServletRequestParameterException e) {
|
||||
// 控制台打印异常
|
||||
e.printStackTrace();
|
||||
return Result.error().setMessage("缺少参数");
|
||||
}
|
||||
|
||||
@ResponseBody
|
||||
@ResponseStatus(HttpStatus.NOT_FOUND)
|
||||
@ExceptionHandler(NoResourceFoundException.class)
|
||||
public Result handleNoResourceFoundException(NoResourceFoundException ex) {
|
||||
ex.printStackTrace();
|
||||
// 新版本 Spring(推荐)我没有这个方法
|
||||
// return ResponseEntity.notFound().body(error);
|
||||
// 旧版本 Spring(兼容写法)
|
||||
return Result.notFound().setMessage("检查网址是否正确");
|
||||
}
|
||||
|
||||
@ResponseBody
|
||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
public Result handleValidationExceptions(MethodArgumentNotValidException ex) {
|
||||
ex.printStackTrace();
|
||||
Map<String, Object> errors = new HashMap<>();
|
||||
ex.getBindingResult().getAllErrors().forEach(error -> {
|
||||
String fieldName = ((FieldError) error).getField();
|
||||
String errorMessage = error.getDefaultMessage();
|
||||
errors.put(fieldName, errorMessage);
|
||||
});
|
||||
return Result.error().setMessage("参数不能为空").setData(errors);
|
||||
}
|
||||
|
||||
// @ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||
// @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
|
||||
// @ResponseBody
|
||||
// public Map<String, String> handleValidationException(Exception ex) {
|
||||
// BindingResult result = ex instanceof MethodArgumentNotValidException
|
||||
// ? ((MethodArgumentNotValidException) ex).getBindingResult()
|
||||
// : ((BindException) ex).getBindingResult();
|
||||
//
|
||||
// Map<String, String> errors = new HashMap<>();
|
||||
// result.getFieldErrors().forEach(error -> {
|
||||
// errors.put(error.getField(), error.getDefaultMessage());
|
||||
// });
|
||||
// return errors;
|
||||
// }
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
package com.mir4updater.backend.result;
|
||||
|
||||
/**
|
||||
* 接口返回工具类
|
||||
*/
|
||||
public class JsonData {
|
||||
private int code;
|
||||
private Object data;
|
||||
private String msg;
|
||||
|
||||
public JsonData() {
|
||||
}
|
||||
|
||||
public JsonData(int code, Object data) {
|
||||
this.code = code;
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
public JsonData(int code, Object data, String msg) {
|
||||
this.code = code;
|
||||
this.data = data;
|
||||
this.msg = msg;
|
||||
}
|
||||
|
||||
public static JsonData buildSuccess(Object data) {
|
||||
return new JsonData(0, data);
|
||||
}
|
||||
|
||||
public static JsonData buildError(String msg) {
|
||||
return new JsonData(-1, "", msg);
|
||||
}
|
||||
|
||||
public static JsonData buildError(int code, String msg) {
|
||||
return new JsonData(code, "", msg);
|
||||
}
|
||||
|
||||
public int getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public void setCode(int code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public Object getData() {
|
||||
return data;
|
||||
}
|
||||
|
||||
public void setData(Object data) {
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
public String getMsg() {
|
||||
return msg;
|
||||
}
|
||||
|
||||
public void setMsg(String msg) {
|
||||
this.msg = msg;
|
||||
}
|
||||
}
|
||||
@@ -1,129 +1,159 @@
|
||||
package com.mir4updater.backend.result;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 统一返回格式类
|
||||
*
|
||||
* @author 爷爷的茶七里香
|
||||
* @date 2022/05/30
|
||||
*/
|
||||
public class Result {
|
||||
|
||||
/**
|
||||
* 是否成功
|
||||
*/
|
||||
private Boolean success;
|
||||
|
||||
/**
|
||||
* 状态码
|
||||
*/
|
||||
private Integer code;
|
||||
|
||||
/**
|
||||
* 返回的消息
|
||||
*/
|
||||
public class Result<T> {
|
||||
// 响应状态
|
||||
private boolean success;
|
||||
// 状态码
|
||||
private int code;
|
||||
// 响应消息
|
||||
private String message;
|
||||
// 响应数据(泛型)
|
||||
private T data;
|
||||
|
||||
/**
|
||||
* 放置响应的数据
|
||||
*/
|
||||
private Map<String, Object> data = new HashMap<>();
|
||||
// 常用状态码常量
|
||||
public static final int CODE_SUCCESS = 200;
|
||||
public static final int CODE_UNKNOWN_REASON = 201;
|
||||
public static final int CODE_ERROR = 500;
|
||||
public static final int CODE_BAD_REQUEST = 400;
|
||||
public static final int CODE_UNAUTHORIZED = 401;
|
||||
public static final int CODE_NOT_FOUND = 404;
|
||||
|
||||
public Result() {
|
||||
// 私有构造方法
|
||||
private Result() {
|
||||
}
|
||||
|
||||
/** 以下是定义一些常用到的格式,可以看到调用了我们创建的枚举类 */
|
||||
|
||||
public static Result ok() {
|
||||
Result r = new Result();
|
||||
r.setSuccess(ResultCodeEnum.SUCCESS.getSuccess());
|
||||
r.setCode(ResultCodeEnum.SUCCESS.getCode());
|
||||
r.setMessage(ResultCodeEnum.SUCCESS.getMessage());
|
||||
return r;
|
||||
}
|
||||
|
||||
public static Result error() {
|
||||
Result r = new Result();
|
||||
r.setSuccess(ResultCodeEnum.UNKNOWN_REASON.getSuccess());
|
||||
r.setCode(ResultCodeEnum.UNKNOWN_REASON.getCode());
|
||||
r.setMessage(ResultCodeEnum.UNKNOWN_REASON.getMessage());
|
||||
return r;
|
||||
}
|
||||
|
||||
public static Result notFound() {
|
||||
Result r = new Result();
|
||||
r.setSuccess(ResultCodeEnum.NOT_FOUND.getSuccess());
|
||||
r.setCode(ResultCodeEnum.NOT_FOUND.getCode());
|
||||
r.setMessage(ResultCodeEnum.NOT_FOUND.getMessage());
|
||||
return r;
|
||||
}
|
||||
|
||||
public static Result setResult(ResultCodeEnum resultCodeEnum) {
|
||||
Result r = new Result();
|
||||
r.setSuccess(resultCodeEnum.getSuccess());
|
||||
r.setCode(resultCodeEnum.getCode());
|
||||
r.setMessage(resultCodeEnum.getMessage());
|
||||
return r;
|
||||
}
|
||||
|
||||
public Result success(Boolean success) {
|
||||
this.setSuccess(success);
|
||||
// 链式调用方法
|
||||
public Result<T> setSuccess(boolean success) {
|
||||
this.success = success;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Result message(String message) {
|
||||
this.setMessage(message);
|
||||
public Result<T> setCode(int code) {
|
||||
this.code = code;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Result code(Integer code) {
|
||||
this.setCode(code);
|
||||
public Result<T> setMessage(String message) {
|
||||
this.message = message;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Result data(String key, Object value) {
|
||||
this.data.put(key, value);
|
||||
public Result<T> setData(T data) {
|
||||
this.data = data;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Result data(Map<String, Object> map) {
|
||||
this.setData(map);
|
||||
return this;
|
||||
}
|
||||
|
||||
/** 以下是get/set方法,如果项目有集成lombok可以使用@Data注解代替 */
|
||||
|
||||
public Boolean getSuccess() {
|
||||
// Getter方法
|
||||
public boolean isSuccess() {
|
||||
return success;
|
||||
}
|
||||
|
||||
public void setSuccess(Boolean success) {
|
||||
this.success = success;
|
||||
}
|
||||
|
||||
public Integer getCode() {
|
||||
public int getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public void setCode(Integer code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public Map<String, Object> getData() {
|
||||
public T getData() {
|
||||
return data;
|
||||
}
|
||||
|
||||
public void setData(Map<String, Object> data) {
|
||||
this.data = data;
|
||||
// 成功静态方法
|
||||
public static <T> Result<T> success() {
|
||||
return success(null);
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> Result<T> success(T data) {
|
||||
return new Result<T>()
|
||||
.setSuccess(true)
|
||||
.setCode(CODE_SUCCESS)
|
||||
.setMessage("操作成功")
|
||||
.setData(data);
|
||||
}
|
||||
|
||||
// 错误静态方法
|
||||
public static <T> Result<T> error() {
|
||||
return error(null);
|
||||
}
|
||||
|
||||
public static <T> Result<T> error(String message) {
|
||||
return error(message, CODE_ERROR);
|
||||
}
|
||||
|
||||
public static <T> Result<T> error(String message, int code) {
|
||||
return new Result<T>()
|
||||
.setSuccess(false)
|
||||
.setCode(code)
|
||||
.setMessage(message);
|
||||
}
|
||||
|
||||
public static <T> Result<T> notFound() {
|
||||
return new Result<T>()
|
||||
.setSuccess(false)
|
||||
.setCode(CODE_NOT_FOUND)
|
||||
.setMessage("没有找到数据");
|
||||
}
|
||||
|
||||
// 快速创建Map类型data(示例)
|
||||
public static Result<Map<String, Object>> mapResult() {
|
||||
return new Result<Map<String, Object>>()
|
||||
.setData(new HashMap<>());
|
||||
}
|
||||
|
||||
public static Result<Map<String, Object>> mapResult(String key, Object value) {
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put(key, value);
|
||||
return new Result<Map<String, Object>>()
|
||||
.setData(map);
|
||||
}
|
||||
|
||||
public static Result<Map<String, Object>> mapResult(Map<String, Object> map) {
|
||||
return new Result<Map<String, Object>>()
|
||||
.setData(map);
|
||||
}
|
||||
|
||||
// 快速创建List类型data(示例)
|
||||
public static <E> Result<List<E>> listResult(List<E> list) {
|
||||
return new Result<List<E>>()
|
||||
.setData(list);
|
||||
}
|
||||
|
||||
|
||||
// 示例用法
|
||||
public static void main(String[] args) {
|
||||
// 1. 返回简单对象
|
||||
Result<User> userResult = Result.success(new User("Alice", 25));
|
||||
|
||||
// 2. 返回Map
|
||||
Map<String, Object> dataMap = new HashMap<>();
|
||||
dataMap.put("page", 1);
|
||||
dataMap.put("total", 100);
|
||||
Result<Map<String, Object>> mapResult = Result.mapResult(dataMap);
|
||||
Result<Map<String, Object>> map = Result.mapResult().setData(dataMap);
|
||||
|
||||
// 3. 返回List
|
||||
Result<List<String>> listResult = Result.listResult(List.of("A", "B", "C"));
|
||||
|
||||
// 4. 错误返回
|
||||
Result<?> errorResult = Result.error("参数校验失败", CODE_BAD_REQUEST);
|
||||
}
|
||||
|
||||
// 示例内部类
|
||||
static class User {
|
||||
private String name;
|
||||
private int age;
|
||||
|
||||
public User(String name, int age) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
// getters/setters...
|
||||
}
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
package com.mir4updater.backend.result;
|
||||
|
||||
/**
|
||||
* 状态码
|
||||
*
|
||||
* @author 爷爷的茶七里香
|
||||
* @date 2022/05/30
|
||||
*/
|
||||
public enum ResultCodeEnum {
|
||||
|
||||
SUCCESS(true, 20000, "成功"),
|
||||
|
||||
UNKNOWN_REASON(false, 20001, "未知错误"),
|
||||
NOT_FOUND(true, 20004, "没有数据");
|
||||
|
||||
|
||||
private final Boolean success;
|
||||
|
||||
private final Integer code;
|
||||
|
||||
private final String message;
|
||||
|
||||
ResultCodeEnum(Boolean success, Integer code, String message) {
|
||||
this.success = success;
|
||||
this.code = code;
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public Boolean getSuccess() {
|
||||
return success;
|
||||
}
|
||||
|
||||
public Integer getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ResultCodeEnum{" + "success=" + success + ", code=" + code + ", message='" + message + '\'' + '}';
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user