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();
        }
    }
  • 相关阅读:
    Installing PHP-7 with Memcached
    在Ubuntu1.4下升级php和Yii2
    apache设置反向代理实现前端js跨域访问
    mysql多重排序判断,根据状态区分时间排序方式
    利用缓存锁解决接口连续访问
    phpstorm启动内存配置
    ubuntu ssh修改用户密码
    Yii2手动安装第三方扩展(转)
    html input file 设置文件类型
    yii2 gridView中使用下拉列表筛选数据
  • 原文地址:https://www.cnblogs.com/zhengyuanyuan/p/10911591.html
Copyright © 2011-2022 走看看