zoukankan      html  css  js  c++  java
  • spring boot全局统一异常处理

    自定义异常

     1 /**
     2  * 自定义异常
     3  * @author Holley
     4  * @create 2018-05-24 14:39
     5  **/
     6 public class SelectNoFindException extends RuntimeException{
     7     /**
     8      * 异常代码
     9      */
    10     private Integer code;
    11     /**
    12      * 自定义错误信息
    13      */
    14     private String erromessage;
    15 
    16     public SelectNoFindException(String erromessage ,String message){
    17         super(message);
    18         this.erromessage = erromessage;
    19     }
    20 
    21     public Integer getCode() {
    22         return code;
    23     }
    24     public String getErromessage() {
    25         return erromessage;
    26     }
    27     public void setCode(Integer code) {
    28         this.code = code;
    29     }
    30     public void setErromessage(String erromessage) {
    31         this.erromessage = erromessage;
    32     }
    33 
    34 }
    View Code

    serviceimpl层代码

    public List<Saler> listSalerContact(Long cid) {
            List<Saler> listSaler = null;
            try {
                listSaler = salerDAO.listSalerContact(cid);
            }catch (Exception e){
                e.printStackTrace();
                throw new  SelectNoFindException("获取订货商列表失败!!",e.getMessage());
            }
            return listSaler;
        }
    View Code

    全局统一异常处理代码

     1 /**
     2  * 全局统一异常处理
     3  * @author Holley
     4  * @create 2018-05-24 14:59
     5  **/
     6 @RestControllerAdvice
     7 public class GlobalExceptionHandler {
     8     private final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
     9 
    10     @ExceptionHandler(value = Exception.class)
    11     public Response handler(Exception e){
    12         Response r = new Response();
    13         if (e instanceof SelectNoFindException){
    14             SelectNoFindException selectNoFindException = (SelectNoFindException) e;
    15             r.setMessage(selectNoFindException.getErromessage());
    16             r.setCode(WhiteListConstant.RESPONSE_CODE_FAIL);
    17             log.error(selectNoFindException.getMessage());
    18             return r;
    19         } else {
    20             r.setCode(WhiteListConstant.RESPONSE_CODE_FAIL);
    21             r.setMessage("系统错误");
    22             log.error(e.getMessage());
    23             return r;
    24         }
    25     }
    26 }
    View Code
  • 相关阅读:
    C#终止线程的方法
    Socket编程(TCP、UDP)
    频率域滤波基础之五(读数字图像处理学习halcon)
    hihoCoder #1127:二分图最小点覆盖和最大独立集
    hihoCoder #1033 : 交错和 (数位Dp)
    HDU-5536 Chip Factory (字典树)
    hihoCoder #1040 (判断是否为矩形)
    hihoCoder:#1079(线段树+离散化)
    HDU-5532 Almost Sorted Array (LIS)
    UVALive-7303 Aquarium (最小生成树)
  • 原文地址:https://www.cnblogs.com/zhlblogs/p/9084270.html
Copyright © 2011-2022 走看看