zoukankan      html  css  js  c++  java
  • 通用异常

    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);
  • 相关阅读:
    由u盘安装Ubuntu引出的事件
    初试Ubuntu
    从error 中学习
    快手一面:牛客:字符串左移
    快手一面:Leetcode:最小栈
    十三、线程池
    十二、windows临界区、其他各种mutex互斥量
    十一、std::async深入
    LeetCode(703):找出数据流中的第K大元素
    LeetCode(1003):检查替换后的字符串
  • 原文地址:https://www.cnblogs.com/feixiangdecainiao/p/10853665.html
Copyright © 2011-2022 走看看