【SpringBoot项目】当代码抛出Exception时,把Exception信息自动发送到钉钉工作群

一、全局异常处理

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);
    }

    /**
     *      * 成功的构造函数
     *      * @param data
     *     
     */
    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;
    }

    /**
     *      * 失败的构造函数
     *      * @param code
     *      * @param msg
     *     
     */
    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);
    }
}


作者:Chainsomkers

来源链接:

https://blog.csdn.net/weixin_44338840/article/details/109492786

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值