spring boot 自定义全局异常及加入钉钉机器人报警

   日期:2020-11-05     浏览:335    评论:0    
核心提示:文章目录一、全局异常处理1、自定义业务异常类2、全局异常处理类二、配置钉钉机器人1、创建钉钉机器人三、整合钉钉机器人一、全局异常处理1、自定义业务异常类某些时候,由于业务逻辑需要抛出自定义异常,这个时候就需要自定义业务异常类。定义CommonException,使他继承于RuntimeException.说明:因为某些业务需要进行业务回滚。但spring的事务只针对RuntimeException的进行回滚操作。所以需要回滚就要继承RuntimeException。public class

文章目录

  • 一、全局异常处理
    • 1、自定义业务异常类
    • 2、全局异常处理类
  • 二、配置钉钉机器人
    • 1、创建钉钉机器人
  • 三、整合钉钉机器人
    • 1、引入jar包
    • 2、发送信息的工具类
    • 3、测试
    • 4、常见报错
  • 四、所用到的工具类


一、全局异常处理


1、自定义业务异常类

某些时候,由于业务逻辑需要抛出自定义异常,这个时候就需要自定义业务异常类。
定义CommonException,使他继承于RuntimeException.

说明:因为某些业务需要进行业务回滚。但spring的事务只针对RuntimeException的进行回滚操作。所以需要回滚就要继承RuntimeException。

public class CommonException extends RuntimeException { 

    private Integer errCode;

    private String errMsg;

    public Integer getErrCode() { 
        return errCode;
    }

    public void setErrCode(Integer errCode) { 
        this.errCode = errCode;
    }

    public String getErrMsg() { 
        return errMsg;
    }

    public void setErrMsg(String errMsg) { 
        this.errMsg = errMsg;
    }

    public CommonException(Integer errCode, String errMsg) { 
        this.errCode = errCode;
        this.errMsg = errMsg;
    }

    public CommonException(String errMsg, Throwable e) { 
        super(errMsg);
        this.errMsg = errMsg;
    }
}

2、全局异常处理类


import com.adleading.daJinMember.common.constant.CodeMsg;
import com.adleading.daJinMember.common.constant.Result;
import com.adleading.daJinMember.common.utils.GlobalUtils;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

@ControllerAdvice
@Component
@Slf4j
public class CommonExceptionHandler { 

    @Autowired
    private GlobalUtils globalUtils;

    @ExceptionHandler
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public Result handle(Exception exception) throws ApiException { 
        if (exception instanceof CommonException) { 
            log.error(exception.getMessage(), exception);
            CommonException e = (CommonException) exception;
            log.error("捕获到异常,异常代码为{},异常信息为{}", e.getErrCode(), e.getErrMsg());
            //发送异常信息到钉钉机器人
            globalUtils.globalMsg(exception);
            return Result.error(new CodeMsg(Integer.valueOf(e.getErrCode()), e.getErrMsg()));
        } else if (exception instanceof HttpMessageNotReadableException) { 
            log.error("前台传入JSON格式错误");
            //发送异常信息到钉钉机器人
            globalUtils.globalMsg(exception);
            return Result.error(CodeMsg.JSON_ERR);
        } else { 
            //发送异常信息到钉钉机器人
            globalUtils.globalMsg(exception);
            log.error("捕获到异常错误");
            return Result.error(CodeMsg.FILES);
        }
    }
}

注意:这里用到的一些工具类,会在文章的结尾处贴出来。



二、配置钉钉机器人

这里给大家简单说了一下如何创建钉钉机器人,如果想深入了解的,点击传送门到官方文档处。

1、创建钉钉机器人

  • 点击左下角更多选择机器人管理

  • 然后选择自定义



  • 添加机器人

1、输入机器人名字并选择要发送消息的群
2、完成必要的安全设置(至少选择一种,博主这里选择了打 √ 的两个)
3、当选择了自定义关键词的时候,在发送报警信息的时候一定要带上关键词。(后面代码演示会指出)


  • 完成设置后,复制出机器人的Webhook地址,可用于向这个群发送消息,格式如下:
https://oapi.dingtalk.com/robot/send?access_token=XXXXXX

三、整合钉钉机器人

1、引入jar包

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>alibaba-dingtalk-service-sdk</artifactId>
    <version>1.0.1</version>
</dependency>

2、发送信息的工具类

当前自定义机器人支持文本 (text)、链接 (link)、markdown(markdown)、ActionCard、FeedCard消息类型。这里就只演示文本 (text)消息类型。


3、测试

  1. Controller层
@Resource
    private TestService testService;

    @GetMapping("/test")
    public Result Test() { 
        testService.test();
        return new Result(CodeMsg.SUCCESS);
    }

2.Service层

@Service
public class TestServiceImpl implements TestService { 


    @Override
    public void test() { 
        int i = 1 / 0;
    }
}

  1. 测试结果如下


4、常见报错

// 消息内容中不包含任何关键词
{
  "errcode":310000,
  "errmsg":"keywords not in content"
}

// timestamp 无效
{
  "errcode":310000,
  "errmsg":"invalid timestamp"
}

// 签名不匹配
{
  "errcode":310000,
  "errmsg":"sign not match"
}

// IP地址不在白名单
{
  "errcode":310000,
  "errmsg":"ip X.X.X.X not in whitelist"
}

四、所用到的工具类

  • CodeMsg类
public class CodeMsg { 
    private int code;
    private String msg;

    public CodeMsg(int code, String msg) { 
        this.code = code;
        this.msg = msg;
    }

    public CodeMsg() { 
    }

    public int getCode() { 
        return code;
    }

    public void setCode(int code) { 
        this.code = code;
    }

    public String getMsg() { 
        return msg;
    }

    public void setMsg(String msg) { 
        this.msg = msg;
    }

    public static CodeMsg SUCCESS = new CodeMsg(200, "success");

    public static CodeMsg FILES = new CodeMsg(300, "未知错误");
    public static CodeMsg JSON_ERR = new CodeMsg(300, "JSON格式错误");

}

  • Result类
@ApiModel(value = "响应结果")
public class Result<T> { 

    @ApiModelProperty(position = 0, value = "状态码", required = true, example = "200200")
    private int code;

    @ApiModelProperty(position = 1, value = "响应信息", required = true, example = "success")
    private String msg;

    @ApiModelProperty(position = 2, value = "响应数据", required = true)
    private T data;

    public int getCode() { 
        return code;
    }

    public void setCode(int code) { 
        this.code = code;
    }

    public String getMsg() { 
        return msg;
    }

    public void setMsg(String msg) { 
        this.msg = msg;
    }

    public T getData() { 
        return data;
    }

    public void setData(T data) { 
        this.data = data;
    }

    
    public static <T> Result<T> success(T data) { 
        return new Result<T>(data);
    }

    
    public static <T> Result<T> error(CodeMsg codeMsg) { 
        return new Result<T>(codeMsg);
    }


    
    private Result(T data) { 
        this.code = 000000;//默认000000是成功
        this.msg = "SUCCESS";
        this.data = data;
    }

    public Result(int code, String msg) { 
        this.code = code;
        this.msg = msg;
    }

    public Result(int code, String msg, T data) { 
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public Result(CodeMsg codeMsg, T data) { 
        this.code = codeMsg.getCode();
        this.msg = codeMsg.getMsg();
        this.data = data;
    }

    
    public Result(CodeMsg codeMsg) { 
        if (codeMsg != null) { 
            this.code = codeMsg.getCode();
            this.msg = codeMsg.getMsg();
        }
    }
}

  • GlobalUtils类
@Component
public class GlobalUtils { 

    @Autowired
    private DingTalkUtils dingTalkUtils;

    public void globalMsg(Exception exception) throws ApiException { 
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw, true);
        exception.printStackTrace(pw);
        String stackTraceString = sw.getBuffer().toString();
        dingTalkUtils.sendMsg(stackTraceString);
    }
}



这篇文件还有很多需要优化的地方,如果有朋友有好的想法或者建议,可以联系我一起交流一下。
 
打赏
 本文转载自:网络 
所有权利归属于原作者,如文章来源标示错误或侵犯了您的权利请联系微信13520258486
更多>最近资讯中心
更多>最新资讯中心
0相关评论

推荐图文
推荐资讯中心
点击排行
最新信息
新手指南
采购商服务
供应商服务
交易安全
关注我们
手机网站:
新浪微博:
微信关注:

13520258486

周一至周五 9:00-18:00
(其他时间联系在线客服)

24小时在线客服