• 通用异常


    1、自定义异常类型参数的枚举类型

    import lombok.AllArgsConstructor;
    import lombok.Getter;
    import lombok.NoArgsConstructor;
    
    @Getter
    @NoArgsConstructor
    @AllArgsConstructor
    public enum ExceptionEnums {
        PRICE_CONNT_BE_NULL(400,"价格不能是空");
        private int code;
        private String msg;
    }

    2、自定义异常

    import com.leyou.common.enums.ExceptionEnums;
    import lombok.AllArgsConstructor;
    import lombok.Getter;
    import lombok.NoArgsConstructor;
    
    @Getter
    @AllArgsConstructor
    @NoArgsConstructor
    public class LyException extends RuntimeException {
        private ExceptionEnums exceptionEnums;
    }

    3、定义统一的异常结果

    import com.leyou.common.enums.ExceptionEnums;
    import lombok.Data;
    
    @Data
    public class ExceptionResult {
        private int status;
        private String message;
        private Long timestamp;
    
        public ExceptionResult(ExceptionEnums em) {
            this.status=em.getCode();
            this.message=em.getMsg();
            this.timestamp=System.currentTimeMillis();
        }
    }

    4定义异常处理器

    import com.leyou.common.exception.LyException;
    import com.leyou.common.vo.ExceptionResult;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    
    @ControllerAdvice  //表示处理带有Controller注解的类
    public class CommonExceptionHandler {
    
        @ExceptionHandler(LyException.class)    //表明拦截的异常类型,这里拦截自己定义的异常
        public ResponseEntity<ExceptionResult> handleExceprion(LyException e){
            return ResponseEntity.status(e.getExceptionEnums().getCode())//通过ResponseEntity设置返回的状态,并且获得状态
                    .body(new ExceptionResult(e.getExceptionEnums()));
        }
    }

    5、使用

    throw new LyException(ExceptionEnums.PRICE_CONNT_BE_NULL);
  • 相关阅读:
    box布局中文字溢出问题
    清除浮动
    react状态提升问题::::
    React两三事
    java直接调用kmeans聚类
    java实现文本词频统计
    java 中list.toArray方法的使用
    java中Map<String,Double>map按照value降序排列
    和声搜索算法java实现
    java 自动打开浏览器并点击
  • 原文地址:https://www.cnblogs.com/feixiangdecainiao/p/10853665.html
Copyright © 2020-2023  润新知