业务实现
后端¶
返回通用对象¶
给对象补充一些信息,告诉前端这个请求在业务层面上是成功还是失败
① 定义全局返回对象
@Data
public class BaseResponse<T> implements Serializable {
private int code;
private T data;
private String msg;
}
② 封装返回工具类
public class ResponseUtils {
public static <T> BaseResponse<T> success(T data) {
BaseResponse<T> response = new BaseResponse<>();
response.setCode(200);
response.setData(data);
response.setMsg("success");
return response;
}
public static <T> BaseResponse<T> error(String msg) {
BaseResponse<T> response = new BaseResponse<>();
response.setCode(500);
response.setMsg(msg);
return response;
}
}
③ 定义Code枚举类型
public enum ErrorCode {
SUCCESS(200, "success"),
ERROR(500, "error");
private final int code;
private final String msg;
ErrorCode(int code, String msg) {
this.code = code;
this.msg = msg;
}
// ...getter
}
封装全局异常处理类¶
1、定义业务异常类
- 相对于Java的异常类,支持更多字段
- 自定义构造函数,更灵活、快捷地设置字段
public class BusinessException extends RuntimeException{
private int code;
private String description;
public BusinessException(int code, String description) {
this.code = code;
this.description = description;
}
}
2、编写全局异常处理器
- 捕获代码中所有的异常,内部消化,让前端得到更详细的业务报错/ 信息
- 屏蔽掉项目框架本身的异常(不暴露服务器内部状态)
- 集中外理,比如记录日志(
@Slf4j
) - Spring AOP:在调用方法前后进行额外的处理
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
@ExceptionHandler(BusinessException.class)
public BaseResponse handleBusinessException(BusinessException e) {
log.error("BusinessException: {}", e.getDescription());
return ResponseUtils.error(e.getCode(), e.getDescription());
}
@ExceptionHandler(RuntimeException.class)
public BaseResponse handleRuntimeException(RuntimeException e) {
log.error("RuntimeException: {}", e.getMessage());
return ResponseUtils.error(e.getMessage());
}
}
前端 - 管理端¶
Git提交跳过husky校验¶
前端 - 用户端¶
路由设计¶
/ → /win
- /win
- /mac
- /linux
- /typeface