zoukankan      html  css  js  c++  java
  • 自定义抛出异常

    可以先定义一个枚举类

    import lombok.AllArgsConstructor;
    import lombok.Getter;
    import lombok.NoArgsConstructor;
    
    @Getter
    @NoArgsConstructor
    @AllArgsConstructor
    public enum ExceptionEnum {
    
        PRICE_CANNOT_BE_NULL(400,"价格不能为空!"),
        CATEGORY_NOT_FOUND(404,"商品分类没查到"),
        ;
        private int code;
        private String msg;
    }

    然后定义一个异常继承EuntimeException

    import lombok.AllArgsConstructor;
    import lombok.Getter;
    import lombok.NoArgsConstructor;
    
    @NoArgsConstructor
    @AllArgsConstructor
    @Getter
    public class LyException extends RuntimeException{
    
        private ExceptionEnum exceptionEnum;
    }

    然后在controller层做拦截

    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
    public class CommonExceptionHandler {
    
        @ExceptionHandler(RuntimeException.class)
        public ResponseEntity<ExceptionResult> handleException(LyException e){
            ExceptionEnum em = e.getExceptionEnum();
            return ResponseEntity.status(em.getCode()).body(new ExceptionResult(e.getExceptionEnum()));
        }
    }

    即可

    也可以加上下行参数实体

    import lombok.Data;
    
    @Data
    public class ExceptionResult {
        private int status;
        private String message;
        private Long timestamp;
    
        public ExceptionResult(ExceptionEnum em){
            this.status = em.getCode();
            this.message = em.getMsg();
            this.timestamp = System.currentTimeMillis();
        }
    }
  • 相关阅读:
    阿里云ECS服务器安装docker
    ActiveMq-常见的问题
    ActiveMq-基础知识
    java语言概述
    【日语词汇类编】自然与人:气候与环境
    【日语词汇类编】传媒与娱乐:大众传播媒介
    机器学习数学基础-线性代数
    掌握机器学习数学基础之概率统计
    机器学习理论篇:机器学习的数学基础
    计算机基础知识
  • 原文地址:https://www.cnblogs.com/zhengyuanyuan/p/10911591.html
Copyright © 2011-2022 走看看