项目搭建模板

1.特殊pom
         <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
        </dependency>
2.ResultVo
@Data
public class ResultVo {
   private Boolean success;

   private Integer code;

   private String message;

   private Map<String, Object> data = new HashMap<>();

   /**
    * 构造器私有
    */
   private ResultVo() {
   }

   /**
    * 通用返回成功
    */
   public static ResultVo ok() {
       ResultVo r = new ResultVo();
       r.setSuccess(ResultCodeEnum.SUCCESS.getSuccess());
       r.setCode(ResultCodeEnum.SUCCESS.getCode());
       r.setMessage(ResultCodeEnum.SUCCESS.getMessage());
       return r;
   }

   /**
    * 通用返回失败,未知错误
    *
    * @return
    */
   public static ResultVo error() {
       ResultVo r = new ResultVo();
       r.setSuccess(ResultCodeEnum.UNKNOWN_ERROR.getSuccess());
       r.setCode(ResultCodeEnum.UNKNOWN_ERROR.getCode());
       r.setMessage(ResultCodeEnum.UNKNOWN_ERROR.getMessage());
       return r;
   }

   /**
    * 设置结果,形参为结果枚举
    *
    * @param result
    * @return
    */
   public static ResultVo setResult(ResultCodeEnum result) {
       ResultVo r = new ResultVo();
       r.setSuccess(result.getSuccess());
       r.setCode(result.getCode());
       r.setMessage(result.getMessage());
       return r;
   }

   /**
    * ------------使用链式编程,返回类本身----------
    * 自定义返回数据
    *
    * @param map
    * @return
    */
   public ResultVo data(Map<String, Object> map) {
       this.setData(map);
       return this;
   }

   /**
    * 通用设置data
    *
    * @param key
    * @param value
    * @return
    */
   public ResultVo data(String key, Object value) {
       this.data.put(key, value);
       return this;
   }

   /**
    * 自定义状态信息
    *
    * @param message
    * @return
    */
   public ResultVo message(String message) {
       this.setMessage(message);
       return this;
   }

   /**
    * 自定义状态码
    *
    * @param code
    * @return
    */
   public ResultVo code(Integer code) {
       this.setCode(code);
       return this;
   }

   /**
    * 自定义返回结果
    *
    * @param success
    * @return
    */
   public ResultVo success(Boolean success) {
       this.setSuccess(success);
       return this;
   }
}
3.ResultCodeEnum
@Getter
public enum ResultCodeEnum {

    SUCCESS(true, 20000, "成功"),
    UNKNOWN_ERROR(false, 20001, "未知错误"),
    PARAM_ERROR(false, 20002, "参数错误"),
    NULL_POINT(false, 20003, "空指针异常"),
    HTTP_CLIENT_ERROR(false, 20004, "客户端连接异常"),
    ;

    /**
     * 响应是否成功
     */
    private Boolean success;
    /**
     * 响应状态码
     */
    private Integer code;
    /**
     * 响应信息
     */
    private String message;

    ResultCodeEnum(boolean success, Integer code, String message) {
        this.success = success;
        this.code = code;
        this.message = message;
    }
}
3.自定义异常和统一异常处理
@Data
public class CMSException extends RuntimeException {
    private Integer code;

    public CMSException(Integer code, String message) {
        super(message);
        this.code = code;
    }

    public CMSException(ResultCodeEnum resultCodeEnum) {
        super(resultCodeEnum.getMessage());
        this.code = resultCodeEnum.getCode();
    }

    @Override
    public String toString() {
        return "CMSException{" + "code=" + code + ", message=" + this.getMessage() + '}';
    }
}
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * -------- 指定异常处理方法 --------
     **/
    @ExceptionHandler(NullPointerException.class)
    @ResponseBody
    public ResultVo error(NullPointerException e) {
        e.printStackTrace();
        return ResultVo.setResult(ResultCodeEnum.NULL_POINT);
    }

    @ExceptionHandler(HttpClientErrorException.class)
    @ResponseBody
    public ResultVo error(IndexOutOfBoundsException e) {
        e.printStackTrace();
        return ResultVo.setResult(ResultCodeEnum.HTTP_CLIENT_ERROR);
    }

    /**
     * -------- 自定义定异常处理方法 --------
     **/
    @ExceptionHandler(CMSException.class)
    @ResponseBody
    public ResultVo error(CMSException e) {
        e.printStackTrace();
        return ResultVo.error().message(e.getMessage()).code(e.getCode());
    }
}
4.日志处理
<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <!-- 格式化输出:%date表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度 %msg:日志消息,%n是换行符-->
    <property name="LOG_PATTERN"
              value="[%d{yyyy-MM-dd HH\:mm\:ss}] [%p] [%c] %m%n" />

    <property name="FILE_PATH" value="N:\\Demo_JAVA\\logs\\%d{yyyy-MM-dd}.%i.log" />

    <!-- 控制台输出日志 -->
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <!-- 按照上面配置的LOG_PATTERN来打印日志 -->
            <pattern>${LOG_PATTERN}</pattern>
        </encoder>
    </appender>

    <!--每天生成一个日志文件,保存30天的日志文件。rollingFile是用来切分文件的 -->
    <appender name="rollingFile"
              class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>
                ${FILE_PATH}
            </fileNamePattern>
            <!-- keep 30 days' worth of history -->
            <maxHistory>30</maxHistory>
            <timeBasedFileNamingAndTriggeringPolicy
                    class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <!-- 日志文件的最大大小 -->
                <maxFileSize>10MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>

        <encoder>
            <pattern>${LOG_PATTERN}</pattern>
        </encoder>
    </appender>

    <!-- 日志输出级别 -->
    <root level="INFO">
        <appender-ref ref="console" />
        <appender-ref ref="rollingFile" />
    </root>

</configuration>
5.实例
@RestController
@RequestMapping("/checkParam")
@Slf4j
public class CheckParam {

    private static final Logger logger = LoggerFactory.getLogger(CheckParam.class);

    @GetMapping("/getBaseEntity")
    public ResultVo getUserStr(@Validated BaseEntity baseEntity, BindingResult result) {

        logger.info("11111111111111111111111111111");

        // throw new CMSException(500,"未知错误");

        return ResultVo.ok().data("baseEntity", baseEntity);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值