增加 CommonResult 的 check 逻辑

pull/4/head
YunaiV 2022-06-17 23:54:42 +08:00
parent ff18d2f30a
commit ca28d791aa
38 changed files with 221 additions and 699 deletions

View File

@ -135,6 +135,11 @@
<artifactId>yudao-spring-boot-starter-biz-social</artifactId> <artifactId>yudao-spring-boot-starter-biz-social</artifactId>
<version>${revision}</version> <version>${revision}</version>
</dependency> </dependency>
<dependency>
<groupId>cn.iocoder.cloud</groupId>
<artifactId>yudao-spring-boot-starter-biz-error-code</artifactId>
<version>${revision}</version>
</dependency>
<!-- Spring 核心 --> <!-- Spring 核心 -->
<dependency> <dependency>

View File

@ -19,6 +19,7 @@
<module>yudao-spring-boot-starter-file</module> <module>yudao-spring-boot-starter-file</module>
<module>yudao-spring-boot-starter-monitor</module> <module>yudao-spring-boot-starter-monitor</module>
<module>yudao-spring-boot-starter-protection</module> <module>yudao-spring-boot-starter-protection</module>
<!-- <module>yudao-spring-boot-starter-config</module>-->
<module>yudao-spring-boot-starter-job</module> <module>yudao-spring-boot-starter-job</module>
<module>yudao-spring-boot-starter-mq</module> <module>yudao-spring-boot-starter-mq</module>
<module>yudao-spring-boot-starter-rpc</module> <module>yudao-spring-boot-starter-rpc</module>
@ -29,12 +30,15 @@
<module>yudao-spring-boot-starter-biz-operatelog</module> <module>yudao-spring-boot-starter-biz-operatelog</module>
<module>yudao-spring-boot-starter-biz-dict</module> <module>yudao-spring-boot-starter-biz-dict</module>
<module>yudao-spring-boot-starter-biz-sms</module> <module>yudao-spring-boot-starter-biz-sms</module>
<module>yudao-spring-boot-starter-activiti</module>
<module>yudao-spring-boot-starter-biz-pay</module> <module>yudao-spring-boot-starter-biz-pay</module>
<module>yudao-spring-boot-starter-biz-weixin</module> <module>yudao-spring-boot-starter-biz-weixin</module>
<module>yudao-spring-boot-starter-biz-social</module> <module>yudao-spring-boot-starter-biz-social</module>
<module>yudao-spring-boot-starter-biz-tenant</module> <module>yudao-spring-boot-starter-biz-tenant</module>
<module>yudao-spring-boot-starter-biz-data-permission</module> <module>yudao-spring-boot-starter-biz-data-permission</module>
<module>yudao-spring-boot-starter-biz-error-code</module>
<module>yudao-spring-boot-starter-activiti</module>
<module>yudao-spring-boot-starter-flowable</module> <module>yudao-spring-boot-starter-flowable</module>
</modules> </modules>

View File

@ -0,0 +1,60 @@
package cn.iocoder.yudao.framework.common.exception;
import cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* Exception
*/
@Data
@EqualsAndHashCode(callSuper = true)
public final class ServerException extends RuntimeException {
/**
*
*
* @see GlobalErrorCodeConstants
*/
private Integer code;
/**
*
*/
private String message;
/**
*
*/
public ServerException() {
}
public ServerException(ErrorCode errorCode) {
this.code = errorCode.getCode();
this.message = errorCode.getMsg();
}
public ServerException(Integer code, String message) {
this.code = code;
this.message = message;
}
public Integer getCode() {
return code;
}
public ServerException setCode(Integer code) {
this.code = code;
return this;
}
@Override
public String getMessage() {
return message;
}
public ServerException setMessage(String message) {
this.message = message;
return this;
}
}

View File

@ -36,9 +36,15 @@ public interface GlobalErrorCodeConstants {
ErrorCode UNKNOWN = new ErrorCode(999, "未知错误"); ErrorCode UNKNOWN = new ErrorCode(999, "未知错误");
static boolean isMatch(Integer code) { /**
* HTTP 5XX
*
* @param code
* @return
*/
static boolean isServerErrorCode(Integer code) {
return code != null return code != null
&& code >= SUCCESS.getCode() && code <= UNKNOWN.getCode(); && code >= INTERNAL_SERVER_ERROR.getCode() && code <= INTERNAL_SERVER_ERROR.getCode() + 99;
} }
} }

View File

@ -95,6 +95,16 @@ public class CommonResult<T> implements Serializable {
throw new ServiceException(code, msg); throw new ServiceException(code, msg);
} }
/**
* {@link ServiceException}
* {@link #data}
*/
@JsonIgnore // 避免 jackson 序列化
public T getCheckedData() {
checkError();
return data;
}
public static <T> CommonResult<T> error(ServiceException serviceException) { public static <T> CommonResult<T> error(ServiceException serviceException) {
return error(serviceException.getCode(), serviceException.getMessage()); return error(serviceException.getCode(), serviceException.getMessage());
} }

View File

@ -106,9 +106,7 @@ public class DeptDataPermissionRule implements DataPermissionRule {
DeptDataPermissionRespDTO deptDataPermission = loginUser.getContext(CONTEXT_KEY, DeptDataPermissionRespDTO.class); DeptDataPermissionRespDTO deptDataPermission = loginUser.getContext(CONTEXT_KEY, DeptDataPermissionRespDTO.class);
// 从上下文中拿不到,则调用逻辑进行获取 // 从上下文中拿不到,则调用逻辑进行获取
if (deptDataPermission == null) { if (deptDataPermission == null) {
CommonResult<DeptDataPermissionRespDTO> getDeptDataPermissionResult = permissionApi.getDeptDataPermission(loginUser.getId()); deptDataPermission = permissionApi.getDeptDataPermission(loginUser.getId()).getData();
getDeptDataPermissionResult.checkError();
deptDataPermission = getDeptDataPermissionResult.getData();
if (deptDataPermission == null) { if (deptDataPermission == null) {
log.error("[getExpression][LoginUser({}) 获取数据权限为 null]", JsonUtils.toJsonString(loginUser)); log.error("[getExpression][LoginUser({}) 获取数据权限为 null]", JsonUtils.toJsonString(loginUser));
throw new NullPointerException(String.format("LoginUser(%d) Table(%s/%s) 未返回数据权限", throw new NullPointerException(String.format("LoginUser(%d) Table(%s/%s) 未返回数据权限",

View File

@ -34,9 +34,8 @@ public class DictFrameworkUtils {
@Override @Override
public DictDataRespDTO load(KeyValue<String, String> key) { public DictDataRespDTO load(KeyValue<String, String> key) {
CommonResult<DictDataRespDTO> getDictDataResult = dictDataApi.getDictData(key.getKey(), key.getValue()); return ObjectUtil.defaultIfNull(dictDataApi.getDictData(key.getKey(), key.getValue()).getCheckedData(),
getDictDataResult.checkError(); DICT_DATA_NULL);
return ObjectUtil.defaultIfNull(getDictDataResult.getData(), DICT_DATA_NULL);
} }
}); });
@ -50,9 +49,8 @@ public class DictFrameworkUtils {
@Override @Override
public DictDataRespDTO load(KeyValue<String, String> key) { public DictDataRespDTO load(KeyValue<String, String> key) {
CommonResult<DictDataRespDTO> parseDictDataResult = dictDataApi.parseDictData(key.getKey(), key.getValue()); return ObjectUtil.defaultIfNull(dictDataApi.parseDictData(key.getKey(), key.getValue()).getCheckedData(),
parseDictDataResult.checkError(); DICT_DATA_NULL);
return ObjectUtil.defaultIfNull(parseDictDataResult.getData(), DICT_DATA_NULL);
} }
}); });

View File

@ -23,8 +23,7 @@ public class OperateLogFrameworkServiceImpl implements OperateLogFrameworkServic
@Async @Async
public void createOperateLog(OperateLog operateLog) { public void createOperateLog(OperateLog operateLog) {
OperateLogCreateReqDTO reqDTO = BeanUtil.copyProperties(operateLog, OperateLogCreateReqDTO.class); OperateLogCreateReqDTO reqDTO = BeanUtil.copyProperties(operateLog, OperateLogCreateReqDTO.class);
CommonResult<Boolean> result = operateLogApi.createOperateLog(reqDTO); operateLogApi.createOperateLog(reqDTO).checkError();
result.checkError();
} }
} }

View File

@ -30,9 +30,7 @@ public class TenantFrameworkServiceImpl implements TenantFrameworkService {
@Override @Override
public List<Long> load(Object key) { public List<Long> load(Object key) {
CommonResult<List<Long>> tenantIdsResult = tenantApi.getTenantIds(); return tenantApi.getTenantIds().getCheckedData();
tenantIdsResult.checkError();
return tenantIdsResult.getData();
} }
}); });

View File

@ -77,9 +77,7 @@ public class TokenAuthenticationFilter extends OncePerRequestFilter {
private LoginUser buildLoginUserByToken(String token, Integer userType) { private LoginUser buildLoginUserByToken(String token, Integer userType) {
try { try {
// 校验访问令牌 // 校验访问令牌
CommonResult<OAuth2AccessTokenCheckRespDTO> accessTokenResult = oauth2TokenApi.checkAccessToken(token); OAuth2AccessTokenCheckRespDTO accessToken = oauth2TokenApi.checkAccessToken(token).getCheckedData();
accessTokenResult.checkError();
OAuth2AccessTokenCheckRespDTO accessToken = accessTokenResult.getData();
if (accessToken == null) { if (accessToken == null) {
return null; return null;
} }

View File

@ -38,13 +38,12 @@ public class SecurityFrameworkServiceImpl implements SecurityFrameworkService {
private final LoadingCache<KeyValue<Long, List<String>>, Boolean> hasAnyRolesCache = CacheUtils.buildAsyncReloadingCache( private final LoadingCache<KeyValue<Long, List<String>>, Boolean> hasAnyRolesCache = CacheUtils.buildAsyncReloadingCache(
Duration.ofMinutes(1L), // 过期时间 1 分钟 Duration.ofMinutes(1L), // 过期时间 1 分钟
new CacheLoader<KeyValue<Long, List<String>>, Boolean>() { new CacheLoader<KeyValue<Long, List<String>>, Boolean>() {
@Override @Override
public Boolean load(KeyValue<Long, List<String>> key) { public Boolean load(KeyValue<Long, List<String>> key) {
CommonResult<Boolean> hasAnyRolesResult = permissionApi.hasAnyRoles(key.getKey(), return permissionApi.hasAnyRoles(key.getKey(), key.getValue().toArray(new String[0])).getCheckedData();
key.getValue().toArray(new String[0]));
hasAnyRolesResult.checkError();
return hasAnyRolesResult.getData();
} }
}); });
/** /**
@ -53,13 +52,12 @@ public class SecurityFrameworkServiceImpl implements SecurityFrameworkService {
private final LoadingCache<KeyValue<Long, List<String>>, Boolean> hasAnyPermissionsCache = CacheUtils.buildAsyncReloadingCache( private final LoadingCache<KeyValue<Long, List<String>>, Boolean> hasAnyPermissionsCache = CacheUtils.buildAsyncReloadingCache(
Duration.ofMinutes(1L), // 过期时间 1 分钟 Duration.ofMinutes(1L), // 过期时间 1 分钟
new CacheLoader<KeyValue<Long, List<String>>, Boolean>() { new CacheLoader<KeyValue<Long, List<String>>, Boolean>() {
@Override @Override
public Boolean load(KeyValue<Long, List<String>> key) { public Boolean load(KeyValue<Long, List<String>> key) {
CommonResult<Boolean> hasAnyPermissionsResult = permissionApi.hasAnyPermissions(key.getKey(), return permissionApi.hasAnyPermissions(key.getKey(), key.getValue().toArray(new String[0])).getCheckedData();
key.getValue().toArray(new String[0]));
hasAnyPermissionsResult.checkError();
return hasAnyPermissionsResult.getData();
} }
}); });
@Override @Override

View File

@ -23,8 +23,7 @@ public class ApiAccessLogFrameworkServiceImpl implements ApiAccessLogFrameworkSe
@Async @Async
public void createApiAccessLog(ApiAccessLog apiAccessLog) { public void createApiAccessLog(ApiAccessLog apiAccessLog) {
ApiAccessLogCreateReqDTO reqDTO = BeanUtil.copyProperties(apiAccessLog, ApiAccessLogCreateReqDTO.class); ApiAccessLogCreateReqDTO reqDTO = BeanUtil.copyProperties(apiAccessLog, ApiAccessLogCreateReqDTO.class);
CommonResult<Boolean> result = apiAccessLogApi.createApiAccessLog(reqDTO); apiAccessLogApi.createApiAccessLog(reqDTO).checkError();
result.checkError();
} }
} }

View File

@ -23,8 +23,7 @@ public class ApiErrorLogFrameworkServiceImpl implements ApiErrorLogFrameworkServ
@Async @Async
public void createApiErrorLog(ApiErrorLog apiErrorLog) { public void createApiErrorLog(ApiErrorLog apiErrorLog) {
ApiErrorLogCreateReqDTO reqDTO = BeanUtil.copyProperties(apiErrorLog, ApiErrorLogCreateReqDTO.class); ApiErrorLogCreateReqDTO reqDTO = BeanUtil.copyProperties(apiErrorLog, ApiErrorLogCreateReqDTO.class);
CommonResult<Boolean> result = apiErrorLogApi.createApiErrorLog(reqDTO); apiErrorLogApi.createApiErrorLog(reqDTO).checkError();
result.checkError();
} }
} }

View File

@ -50,9 +50,7 @@ public interface FileApi {
default String createFile(@RequestParam("name") String name, default String createFile(@RequestParam("name") String name,
@RequestParam("path") String path, @RequestParam("path") String path,
@RequestParam("content") byte[] content) { @RequestParam("content") byte[] content) {
CommonResult<String> result = createFile(new FileCreateReqDTO().setName(name).setPath(path).setContent(content)); return createFile(new FileCreateReqDTO().setName(name).setPath(path).setContent(content)).getCheckedData();
result.checkError();
return result.getData();
} }
@PostMapping(PREFIX + "/create") @PostMapping(PREFIX + "/create")

View File

@ -44,9 +44,7 @@ public interface DeptApi {
* @return Map * @return Map
*/ */
default Map<Long, DeptRespDTO> getDeptMap(Set<Long> ids) { default Map<Long, DeptRespDTO> getDeptMap(Set<Long> ids) {
CommonResult<List<DeptRespDTO>> result = getDepts(ids); return CollectionUtils.convertMap(getDepts(ids).getCheckedData(), DeptRespDTO::getId);
result.checkError();
return CollectionUtils.convertMap(result.getData(), DeptRespDTO::getId);
} }
} }

View File

@ -0,0 +1,40 @@
package cn.iocoder.yudao.module.system.api.errorcode;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.system.api.errorcode.dto.ErrorCodeAutoGenerateReqDTO;
import cn.iocoder.yudao.module.system.api.errorcode.dto.ErrorCodeRespDTO;
import cn.iocoder.yudao.module.system.enums.ApiConstants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
@FeignClient(name = ApiConstants.NAME) // TODO 芋艿fallbackFactory =
@Api(tags = "RPC 服务 - 错误码")
public interface ErrorCodeApi {
String PREFIX = ApiConstants.PREFIX + "/oauth2/token";
@PostMapping(PREFIX + "/auto-generate")
@ApiOperation("自动创建错误码")
CommonResult<Boolean> autoGenerateErrorCodes(@Valid @RequestBody List<ErrorCodeAutoGenerateReqDTO> autoGenerateDTOs);
@GetMapping(PREFIX + "/list")
@ApiOperation(value = "增量获得错误码数组", notes = "如果 minUpdateTime 为空时,则获取所有错误码")
@ApiImplicitParams({
@ApiImplicitParam(name = "applicationName", value = "应用名", example = "system-server", required = true, dataTypeClass = String.class),
@ApiImplicitParam(name = "minUpdateTime", value = "最小更新时间", dataTypeClass = Date.class)
})
CommonResult<List<ErrorCodeRespDTO>> getErrorCodeList(@RequestParam(value = "applicationName") String applicationName,
@RequestParam(value = "minUpdateTime", required = false) Date minUpdateTime);
}

View File

@ -1,4 +1,4 @@
package cn.iocoder.yudao.module.system.framework.errorcode.core.dto; package cn.iocoder.yudao.module.system.api.errorcode.dto;
import lombok.Data; import lombok.Data;
import lombok.experimental.Accessors; import lombok.experimental.Accessors;

View File

@ -1,4 +1,4 @@
package cn.iocoder.yudao.module.system.framework.errorcode.core.dto; package cn.iocoder.yudao.module.system.api.errorcode.dto;
import lombok.Data; import lombok.Data;

View File

@ -49,9 +49,7 @@ public interface AdminUserApi {
* @return Map * @return Map
*/ */
default Map<Long, AdminUserRespDTO> getUserMap(Collection<Long> ids) { default Map<Long, AdminUserRespDTO> getUserMap(Collection<Long> ids) {
CommonResult<List<AdminUserRespDTO>> getUsersResult = getUsers(ids); return CollectionUtils.convertMap(getUsers(ids).getCheckedData(), AdminUserRespDTO::getId);
getUsersResult.checkError();
return CollectionUtils.convertMap(getUsersResult.getData(), AdminUserRespDTO::getId);
} }
@GetMapping(PREFIX + "/valid") @GetMapping(PREFIX + "/valid")

View File

@ -61,6 +61,10 @@
<groupId>cn.iocoder.cloud</groupId> <groupId>cn.iocoder.cloud</groupId>
<artifactId>yudao-spring-boot-starter-biz-tenant</artifactId> <artifactId>yudao-spring-boot-starter-biz-tenant</artifactId>
</dependency> </dependency>
<dependency>
<groupId>cn.iocoder.cloud</groupId>
<artifactId>yudao-spring-boot-starter-biz-error-code</artifactId>
</dependency>
<!-- Web 相关 --> <!-- Web 相关 -->
<dependency> <dependency>

View File

@ -0,0 +1,36 @@
package cn.iocoder.yudao.module.system.api.errorcode;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.system.api.errorcode.dto.ErrorCodeAutoGenerateReqDTO;
import cn.iocoder.yudao.module.system.api.errorcode.dto.ErrorCodeRespDTO;
import cn.iocoder.yudao.module.system.service.errorcode.ErrorCodeService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.module.system.enums.ApiConstants.VERSION;
@RestController // 提供 RESTful API 接口,给 Feign 调用
@DubboService(version = VERSION) // 提供 Dubbo RPC 接口,给 Dubbo Consumer 调用
@Validated
public class ErrorCodeApiImpl implements ErrorCodeApi {
@Resource
private ErrorCodeService errorCodeService;
@Override
public CommonResult<Boolean> autoGenerateErrorCodes(List<ErrorCodeAutoGenerateReqDTO> autoGenerateDTOs) {
errorCodeService.autoGenerateErrorCodes(autoGenerateDTOs);
return success(true);
}
@Override
public CommonResult<List<ErrorCodeRespDTO>> getErrorCodeList(String applicationName, Date minUpdateTime) {
return success(errorCodeService.getErrorCodeList(applicationName, minUpdateTime));
}
}

View File

@ -1,12 +1,12 @@
package cn.iocoder.yudao.module.system.convert.errorcode; package cn.iocoder.yudao.module.system.convert.errorcode;
import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.system.api.errorcode.dto.ErrorCodeAutoGenerateReqDTO;
import cn.iocoder.yudao.module.system.api.errorcode.dto.ErrorCodeRespDTO;
import cn.iocoder.yudao.module.system.controller.admin.errorcode.vo.ErrorCodeCreateReqVO; import cn.iocoder.yudao.module.system.controller.admin.errorcode.vo.ErrorCodeCreateReqVO;
import cn.iocoder.yudao.module.system.controller.admin.errorcode.vo.ErrorCodeExcelVO; import cn.iocoder.yudao.module.system.controller.admin.errorcode.vo.ErrorCodeExcelVO;
import cn.iocoder.yudao.module.system.controller.admin.errorcode.vo.ErrorCodeRespVO; import cn.iocoder.yudao.module.system.controller.admin.errorcode.vo.ErrorCodeRespVO;
import cn.iocoder.yudao.module.system.dal.dataobject.errorcode.ErrorCodeDO; import cn.iocoder.yudao.module.system.dal.dataobject.errorcode.ErrorCodeDO;
import cn.iocoder.yudao.module.system.framework.errorcode.core.dto.ErrorCodeAutoGenerateReqDTO;
import cn.iocoder.yudao.module.system.framework.errorcode.core.dto.ErrorCodeRespDTO;
import cn.iocoder.yudao.module.system.controller.admin.errorcode.vo.ErrorCodeUpdateReqVO; import cn.iocoder.yudao.module.system.controller.admin.errorcode.vo.ErrorCodeUpdateReqVO;
import org.mapstruct.Mapper; import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers; import org.mapstruct.factory.Mappers;

View File

@ -1,35 +0,0 @@
package cn.iocoder.yudao.module.system.framework.errorcode.core.service;
import cn.iocoder.yudao.module.system.framework.errorcode.core.dto.ErrorCodeAutoGenerateReqDTO;
import cn.iocoder.yudao.module.system.framework.errorcode.core.dto.ErrorCodeRespDTO;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
/**
* Framework Service
*
* @author
*/
public interface ErrorCodeFrameworkService {
/**
*
*
* @param autoGenerateDTOs
*/
void autoGenerateErrorCodes(@Valid List<ErrorCodeAutoGenerateReqDTO> autoGenerateDTOs);
/**
*
*
* minUpdateTime
*
* @param applicationName
* @param minUpdateTime
* @return
*/
List<ErrorCodeRespDTO> getErrorCodeList(String applicationName, Date minUpdateTime);
}

View File

@ -1,6 +0,0 @@
/**
*
*
* n
*/
package cn.iocoder.yudao.module.system.framework.errorcode;

View File

@ -1,14 +1,16 @@
package cn.iocoder.yudao.module.system.service.errorcode; package cn.iocoder.yudao.module.system.service.errorcode;
import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.system.api.errorcode.dto.ErrorCodeAutoGenerateReqDTO;
import cn.iocoder.yudao.module.system.api.errorcode.dto.ErrorCodeRespDTO;
import cn.iocoder.yudao.module.system.dal.dataobject.errorcode.ErrorCodeDO; import cn.iocoder.yudao.module.system.dal.dataobject.errorcode.ErrorCodeDO;
import cn.iocoder.yudao.module.system.framework.errorcode.core.service.ErrorCodeFrameworkService;
import cn.iocoder.yudao.module.system.controller.admin.errorcode.vo.ErrorCodeCreateReqVO; import cn.iocoder.yudao.module.system.controller.admin.errorcode.vo.ErrorCodeCreateReqVO;
import cn.iocoder.yudao.module.system.controller.admin.errorcode.vo.ErrorCodeExportReqVO; import cn.iocoder.yudao.module.system.controller.admin.errorcode.vo.ErrorCodeExportReqVO;
import cn.iocoder.yudao.module.system.controller.admin.errorcode.vo.ErrorCodePageReqVO; import cn.iocoder.yudao.module.system.controller.admin.errorcode.vo.ErrorCodePageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.errorcode.vo.ErrorCodeUpdateReqVO; import cn.iocoder.yudao.module.system.controller.admin.errorcode.vo.ErrorCodeUpdateReqVO;
import javax.validation.Valid; import javax.validation.Valid;
import java.util.Date;
import java.util.List; import java.util.List;
/** /**
@ -16,7 +18,25 @@ import java.util.List;
* *
* @author * @author
*/ */
public interface ErrorCodeService extends ErrorCodeFrameworkService { public interface ErrorCodeService {
/**
*
*
* @param autoGenerateDTOs
*/
void autoGenerateErrorCodes(@Valid List<ErrorCodeAutoGenerateReqDTO> autoGenerateDTOs);
/**
*
*
* minUpdateTime
*
* @param applicationName
* @param minUpdateTime
* @return
*/
List<ErrorCodeRespDTO> getErrorCodeList(String applicationName, Date minUpdateTime);
/** /**
* *

View File

@ -2,14 +2,14 @@ package cn.iocoder.yudao.module.system.service.errorcode;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.system.api.errorcode.dto.ErrorCodeAutoGenerateReqDTO;
import cn.iocoder.yudao.module.system.api.errorcode.dto.ErrorCodeRespDTO;
import cn.iocoder.yudao.module.system.controller.admin.errorcode.vo.ErrorCodeCreateReqVO; import cn.iocoder.yudao.module.system.controller.admin.errorcode.vo.ErrorCodeCreateReqVO;
import cn.iocoder.yudao.module.system.controller.admin.errorcode.vo.ErrorCodeUpdateReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.errorcode.ErrorCodeDO;
import cn.iocoder.yudao.module.system.framework.errorcode.core.dto.ErrorCodeAutoGenerateReqDTO;
import cn.iocoder.yudao.module.system.framework.errorcode.core.dto.ErrorCodeRespDTO;
import cn.iocoder.yudao.module.system.convert.errorcode.ErrorCodeConvert;
import cn.iocoder.yudao.module.system.controller.admin.errorcode.vo.ErrorCodeExportReqVO; import cn.iocoder.yudao.module.system.controller.admin.errorcode.vo.ErrorCodeExportReqVO;
import cn.iocoder.yudao.module.system.controller.admin.errorcode.vo.ErrorCodePageReqVO; import cn.iocoder.yudao.module.system.controller.admin.errorcode.vo.ErrorCodePageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.errorcode.vo.ErrorCodeUpdateReqVO;
import cn.iocoder.yudao.module.system.convert.errorcode.ErrorCodeConvert;
import cn.iocoder.yudao.module.system.dal.dataobject.errorcode.ErrorCodeDO;
import cn.iocoder.yudao.module.system.dal.mysql.errorcode.ErrorCodeMapper; import cn.iocoder.yudao.module.system.dal.mysql.errorcode.ErrorCodeMapper;
import cn.iocoder.yudao.module.system.enums.errorcode.ErrorCodeTypeEnum; import cn.iocoder.yudao.module.system.enums.errorcode.ErrorCodeTypeEnum;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
@ -24,9 +24,10 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertMap; import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertMap;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet; import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.ERROR_CODE_DUPLICATE;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.ERROR_CODE_NOT_EXISTS;
/** /**
* Service * Service

View File

@ -1,8 +1,8 @@
package cn.iocoder.yudao.module.system.service.errorcode; package cn.iocoder.yudao.module.system.service.errorcode;
import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.system.api.errorcode.dto.ErrorCodeAutoGenerateReqDTO;
import cn.iocoder.yudao.module.system.dal.dataobject.errorcode.ErrorCodeDO; import cn.iocoder.yudao.module.system.dal.dataobject.errorcode.ErrorCodeDO;
import cn.iocoder.yudao.module.system.framework.errorcode.core.dto.ErrorCodeAutoGenerateReqDTO;
import cn.iocoder.yudao.module.system.controller.admin.errorcode.vo.ErrorCodeCreateReqVO; import cn.iocoder.yudao.module.system.controller.admin.errorcode.vo.ErrorCodeCreateReqVO;
import cn.iocoder.yudao.module.system.controller.admin.errorcode.vo.ErrorCodeExportReqVO; import cn.iocoder.yudao.module.system.controller.admin.errorcode.vo.ErrorCodeExportReqVO;
import cn.iocoder.yudao.module.system.controller.admin.errorcode.vo.ErrorCodePageReqVO; import cn.iocoder.yudao.module.system.controller.admin.errorcode.vo.ErrorCodePageReqVO;

View File

@ -1,33 +0,0 @@
package cn.iocoder.common.framework.util;
import java.util.Random;
public class MathUtil {
/**
*
*/
private static final Random RANDOM = new Random(); // TODO 后续优化
/**
* [min, max]
*
* @param min
* @param max
* @return
*/
public static int random(int min, int max) {
if (min == max) {
return min;
}
if (min > max) {
int temp = min;
min = max;
max = temp;
}
// 随即开始
int diff = max - min + 1;
return RANDOM.nextInt(diff) + min;
}
}

View File

@ -1,14 +0,0 @@
package cn.iocoder.common.framework.util;
import cn.hutool.system.SystemUtil;
/**
*
*/
public class OSUtils {
public static String getHostName() {
return SystemUtil.getHostInfo().getName();
}
}

View File

@ -1,154 +0,0 @@
package cn.iocoder.common.framework.vo;
import cn.iocoder.common.framework.exception.ErrorCode;
import cn.iocoder.common.framework.exception.GlobalException;
import cn.iocoder.common.framework.exception.ServiceException;
import cn.iocoder.common.framework.exception.enums.GlobalErrorCodeConstants;
import com.alibaba.fastjson.annotation.JSONField;
import org.springframework.util.Assert;
import java.io.Serializable;
/**
*
*
* @param <T>
*/
public final class CommonResult<T> implements Serializable {
/**
*
*
* @see ErrorCode#getCode()
*/
private Integer code;
/**
*
*/
private T data;
/**
*
*
* @see ErrorCode#getMessage() ()
*/
private String message;
/**
*
*/
private String detailMessage;
/**
* result
*
* A CommonResult B
*
* @param result result
* @param <T>
* @return CommonResult
*/
public static <T> CommonResult<T> error(CommonResult<?> result) {
return error(result.getCode(), result.getMessage(), result.detailMessage);
}
public static <T> CommonResult<T> error(Integer code, String message) {
return error(code, message, null);
}
public static <T> CommonResult<T> error(Integer code, String message, String detailMessage) {
Assert.isTrue(!GlobalErrorCodeConstants.SUCCESS.getCode().equals(code), "code 必须是错误的!");
CommonResult<T> result = new CommonResult<>();
result.code = code;
result.message = message;
result.detailMessage = detailMessage;
return result;
}
public static <T> CommonResult<T> success(T data) {
CommonResult<T> result = new CommonResult<>();
result.code = GlobalErrorCodeConstants.SUCCESS.getCode();
result.data = data;
result.message = "";
return result;
}
public Integer 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 T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public String getDetailMessage() {
return detailMessage;
}
public CommonResult<T> setDetailMessage(String detailMessage) {
this.detailMessage = detailMessage;
return this;
}
@JSONField(serialize = false) // 避免序列化
public boolean isSuccess() {
return GlobalErrorCodeConstants.SUCCESS.getCode().equals(code);
}
@JSONField(serialize = false) // 避免序列化
public boolean isError() {
return !isSuccess();
}
@Override
public String toString() {
return "CommonResult{" +
"code=" + code +
", data=" + data +
", message='" + message + '\'' +
", detailMessage='" + detailMessage + '\'' +
'}';
}
// ========= 和 Exception 异常体系集成 =========
/**
* {@link GlobalException} {@link ServiceException}
*/
public void checkError() throws GlobalException, ServiceException {
if (isSuccess()) {
return;
}
// 全局异常
if (GlobalErrorCodeConstants.isMatch(code)) {
throw new GlobalException(code, message).setDetailMessage(detailMessage);
}
// 业务异常
throw new ServiceException(code, message).setDetailMessage(detailMessage);
}
public static <T> CommonResult<T> error(ServiceException serviceException) {
return error(serviceException.getCode(), serviceException.getMessage(),
serviceException.getDetailMessage());
}
public static <T> CommonResult<T> error(GlobalException globalException) {
return error(globalException.getCode(), globalException.getMessage(),
globalException.getDetailMessage());
}
}

View File

@ -1,46 +0,0 @@
package cn.iocoder.common.framework.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.hibernate.validator.constraints.Range;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
@ApiModel("分页参数")
public class PageParam implements Serializable {
@ApiModelProperty(value = "页码,从 1 开始", required = true,example = "1")
@NotNull(message = "页码不能为空")
@Min(value = 1, message = "页码最小值为 1")
private Integer pageNo;
@ApiModelProperty(value = "每页条数,最大值为 100", required = true, example = "10")
@NotNull(message = "每页条数不能为空")
@Range(min = 1, max = 100, message = "条数范围为 [1, 100]")
private Integer pageSize;
public Integer getPageNo() {
return pageNo;
}
public PageParam setPageNo(Integer pageNo) {
this.pageNo = pageNo;
return this;
}
public Integer getPageSize() {
return pageSize;
}
public PageParam setPageSize(Integer pageSize) {
this.pageSize = pageSize;
return this;
}
// public final int getOffset() {
// return (pageNo - 1) * pageSize;
// }
}

View File

@ -1,36 +0,0 @@
package cn.iocoder.common.framework.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.util.List;
@ApiModel("分页结果")
public final class PageResult<T> implements Serializable {
@ApiModelProperty(value = "数据", required = true)
private List<T> list;
@ApiModelProperty(value = "总量", required = true)
private Long total;
public List<T> getList() {
return list;
}
public PageResult<T> setList(List<T> list) {
this.list = list;
return this;
}
public Long getTotal() {
return total;
}
public PageResult<T> setTotal(Long total) {
this.total = total;
return this;
}
}

View File

@ -1,56 +0,0 @@
package cn.iocoder.common.framework.vo;
import java.io.Serializable;
/**
* DTO
*
* ing ES SortField
*/
public class SortingField implements Serializable {
/**
* -
*/
public static final String ORDER_ASC = "asc";
/**
* -
*/
public static final String ORDER_DESC = "desc";
/**
*
*/
private String field;
/**
*
*/
private String order;
// 空构造方法,解决反序列化
public SortingField() {
}
public SortingField(String field, String order) {
this.field = field;
this.order = order;
}
public String getField() {
return field;
}
public SortingField setField(String field) {
this.field = field;
return this;
}
public String getOrder() {
return order;
}
public SortingField setOrder(String order) {
this.order = order;
return this;
}
}

View File

@ -1,46 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>common</artifactId>
<groupId>cn.iocoder.mall</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>mall-spring-boot-starter-system-error-code</artifactId>
<description>
错误码 ErrorCode 的自动配置功能,提供如下功能:
1. 远程读取:项目启动时,从 system-service 服务,读取数据库中的 ErrorCode 错误码,实现错误码的提水可配置;
2. 自动更新:管理员在管理后台修数据库中的 ErrorCode 错误码时,项目自动从 system-service 服务加载最新的 ErrorCode 错误码;
3. 自动写入:项目启动时,将项目本地的错误码写到 system-service 服务中,方便管理员在管理后台编辑;
</description>
<dependencies>
<!-- Mall 相关 -->
<dependency>
<groupId>cn.iocoder.mall</groupId>
<artifactId>system-service-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!-- Spring 核心 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!-- RPC 相关 -->
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo</artifactId>
</dependency>
</dependencies>
</project>

View File

@ -1,26 +0,0 @@
package cn.iocoder.mall.system.errorcode.config;
import cn.iocoder.mall.system.errorcode.core.ErrorCodeAutoGenerator;
import cn.iocoder.mall.system.errorcode.core.ErrorCodeRemoteLoader;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@EnableConfigurationProperties(ErrorCodeProperties.class)
@EnableScheduling // 开启调度任务的功能,因为 ErrorCodeRemoteLoader 通过定时刷新错误码
public class ErrorCodeAutoConfiguration {
// @Bean
// public ErrorCodeAutoGenerator errorCodeAutoGenerator(ErrorCodeProperties errorCodeProperties) {
// return new ErrorCodeAutoGenerator(errorCodeProperties.getGroup())
// .setErrorCodeConstantsClass(errorCodeProperties.getConstantsClass());
// }
//
// @Bean
// public ErrorCodeRemoteLoader errorCodeRemoteLoader(ErrorCodeProperties errorCodeProperties) {
// return new ErrorCodeRemoteLoader(errorCodeProperties.getGroup());
// }
}

View File

@ -1,39 +0,0 @@
package cn.iocoder.mall.system.errorcode.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.NotNull;
@ConfigurationProperties("mall.error-code")
@Validated
public class ErrorCodeProperties {
/**
*
*/
@NotNull(message = "应用分组不能为空,请设置 mall.error-code.group 配置项,推荐直接使用 spring. application.name 配置项")
private String group;
/**
*
*/
private String constantsClass;
public String getGroup() {
return group;
}
public ErrorCodeProperties setGroup(String group) {
this.group = group;
return this;
}
public String getConstantsClass() {
return constantsClass;
}
public ErrorCodeProperties setConstantsClass(String constantsClass) {
this.constantsClass = constantsClass;
return this;
}
}

View File

@ -1,84 +0,0 @@
package cn.iocoder.mall.system.errorcode.core;
import cn.iocoder.common.framework.exception.ErrorCode;
import cn.iocoder.common.framework.util.StringUtils;
import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.mall.systemservice.rpc.errorcode.ErrorCodeFeign;
import cn.iocoder.mall.systemservice.rpc.errorcode.dto.ErrorCodeAutoGenerateDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ErrorCodeAutoGenerator {
//
// private Logger logger = LoggerFactory.getLogger(ErrorCodeAutoGenerator.class);
//
// /**
// * 应用分组
// */
// private final String group;
// /**
// * 错误码枚举类
// */
// private String errorCodeConstantsClass;
//
//
// @Autowired
// private ErrorCodeFeign errorCodeFeign;
// public ErrorCodeAutoGenerator(String group) {
// this.group = group;
// }
//
// public ErrorCodeAutoGenerator setErrorCodeConstantsClass(String errorCodeConstantsClass) {
// this.errorCodeConstantsClass = errorCodeConstantsClass;
// return this;
// }
//
// @EventListener(ApplicationReadyEvent.class)
// @Async // 异步,保证项目的启动过程,毕竟非关键流程
// public void execute() {
// // 校验 errorCodeConstantsClass 参数
// if (!StringUtils.hasText(errorCodeConstantsClass)) {
// logger.info("[execute][未配置 mall.error-code.constants-class 配置项,不进行自动写入到 system-service 服务]");
// return;
// }
// Class errorCodeConstantsClazz;
// try {
// errorCodeConstantsClazz = Class.forName(errorCodeConstantsClass);
// } catch (ClassNotFoundException e) {
// logger.error("[execute][配置的 ({}) 找不到对应的类]", errorCodeConstantsClass);
// return;
// }
// // 写入 system-service 服务
// logger.info("[execute][自动将 ({}) 类的错误码,准备写入到 system-service 服务]", errorCodeConstantsClass);
// List<ErrorCodeAutoGenerateDTO> autoGenerateDTOs = new ArrayList<>();
// Arrays.stream(errorCodeConstantsClazz.getFields()).forEach(field -> {
// if (field.getType() != ErrorCode.class) {
// return;
// }
// try {
// // TODO 芋艿:校验是否重复了;
// ErrorCode errorCode = (ErrorCode) field.get(errorCodeConstantsClazz);
// autoGenerateDTOs.add(new ErrorCodeAutoGenerateDTO().setGroup(group)
// .setCode(errorCode.getCode()).setMessage(errorCode.getMessage()));
// } catch (IllegalAccessException e) {
// throw new RuntimeException(e);
// }
// });
// CommonResult<Boolean> autoGenerateErrorCodesResult = errorCodeFeign.autoGenerateErrorCodes(autoGenerateDTOs);
// if (autoGenerateErrorCodesResult.isSuccess()) {
// logger.info("[execute][自动将 ({}) 类的错误码,成功写入到 system-service 服务]", errorCodeConstantsClass);
// } else {
// logger.error("[execute][自动将 ({}) 类的错误码,失败写入到 system-service 服务,原因为 ({}/{}/{})]", errorCodeConstantsClass,
// autoGenerateErrorCodesResult.getCode(), autoGenerateErrorCodesResult.getMessage(), autoGenerateErrorCodesResult.getDetailMessage());
// }
// }
}

View File

@ -1,70 +0,0 @@
package cn.iocoder.mall.system.errorcode.core;
import cn.iocoder.common.framework.exception.util.ServiceExceptionUtil;
import cn.iocoder.common.framework.util.CollectionUtils;
import cn.iocoder.common.framework.util.DateUtil;
import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.mall.systemservice.rpc.errorcode.ErrorCodeFeign;
import cn.iocoder.mall.systemservice.rpc.errorcode.vo.ErrorCodeVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Scheduled;
import java.util.Date;
import java.util.List;
public class ErrorCodeRemoteLoader {
//
// private static final int REFRESH_ERROR_CODE_PERIOD = 60 * 1000;
//
// private Logger logger = LoggerFactory.getLogger(ErrorCodeRemoteLoader.class);
//
// /**
// * 应用分组
// */
// private final String group;
//
// @Autowired
// private ErrorCodeFeign errorCodeFeign;
// private Date maxUpdateTime;
//
// public ErrorCodeRemoteLoader(String group) {
// this.group = group;
// }
//
// @EventListener(ApplicationReadyEvent.class)
// public void loadErrorCodes() {
// // 从 errorCodeFeign 全量加载 ErrorCode 错误码
// CommonResult<List<ErrorCodeVO>> listErrorCodesResult = errorCodeFeign.listErrorCodes(group, null);
// listErrorCodesResult.checkError();
// logger.info("[loadErrorCodes][从 group({}) 全量加载到 {} 个 ErrorCode 错误码]", group, listErrorCodesResult.getData().size());
// // 写入到 ServiceExceptionUtil 到
// listErrorCodesResult.getData().forEach(errorCodeVO -> {
// ServiceExceptionUtil.put(errorCodeVO.getCode(), errorCodeVO.getMessage());
// // 记录下更新时间,方便增量更新
// maxUpdateTime = DateUtil.max(maxUpdateTime, errorCodeVO.getUpdateTime());
// });
// }
//
// @Scheduled(fixedDelay = REFRESH_ERROR_CODE_PERIOD, initialDelay = REFRESH_ERROR_CODE_PERIOD)
// public void refreshErrorCodes() {
// // 从 errorCodeFeign 增量加载 ErrorCode 错误码
// // TODO 优化点:假设删除错误码的配置,会存在问题;
// CommonResult<List<ErrorCodeVO>> listErrorCodesResult = errorCodeFeign.listErrorCodes(group, maxUpdateTime);
// listErrorCodesResult.checkError();
// if (CollectionUtils.isEmpty(listErrorCodesResult.getData())) {
// return;
// }
// logger.info("[refreshErrorCodes][从 group({}) 增量加载到 {} 个 ErrorCode 错误码]", group, listErrorCodesResult.getData().size());
// // 写入到 ServiceExceptionUtil 到
// listErrorCodesResult.getData().forEach(errorCodeVO -> {
// ServiceExceptionUtil.put(errorCodeVO.getCode(), errorCodeVO.getMessage());
// // 记录下更新时间,方便增量更新
// maxUpdateTime = DateUtil.max(maxUpdateTime, errorCodeVO.getUpdateTime());
// });
// }
}