[Alarm notification] Unified exception capture and processing for Java projects [Dingding alarm push message]

Basic description

  • In actual business, system business exceptions are often obtained passively. For example, when a certain function is not working through the business department or customer feedback, the system appears to be passive and dull.
  • In SpringBoot, there is unified exception handling that can be implemented. When we detect non-business exceptions, such as null pointer exceptions, array out-of-bounds exceptions, etc.
  • We can actively know the time and business scenarios when the exception occurs, so that the system can actively capture the exception and quickly locate and process it
  • But they have all encountered the same thing - system abnormalities lead to losses. This seems to be something every company has to go through
  • Regardless of whether it is the e-commerce industry or the financial industry, any business involving transactions will actually have great systemic risks. For example, if the system or interface is abnormal, the user cannot complete the transaction, which is a loss of transaction volume for the company. Another example is that improper operation of the operating personnel leads to being swiped or scammed, which is a loss of profit for the company.
    insert image description here

DingTalk robot creation

new group

  • Create a DingTalk group to receive alarm messages
    insert image description here
    insert image description here

Create a new DingTalk robot

  • Click group settings
    insert image description here
  • click bot
    insert image description here
  • choose custom
    insert image description here
  • configure
    insert image description here
    insert image description here
  • Save the key and webhook notification address
  • received warning message
    insert image description here

Unified exception capture

  • Unified exception handling
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    
    

    @Autowired
    DingMsgService dingMsgService;

    @ExceptionHandler(Exception.class)
    public R handleException(Exception e) {
    
    
        log.error(e.getMessage(), e);
        try {
    
    
            // 后续数据可入库
            dingMsgService.sendDingTalkMsg(JSONObject.toJSONString(e));
        } catch (Exception ee) {
    
    
            log.error("发送异常信息接口异常", ee);
        }
        return R.fail(e.getMessage());
    }
}

Send DingTalk message

  • configure yaml
# 公共配置
config:
  dingtalk:
    secret: SECe1a978f33f20ec1e91091a91ff52a3d2da0bb1afb48ef69d183ec9de7d35681f
    webhook: https://oapi.dingtalk.com/robot/send?access_token=20347ef4a6b6a8086227f5c36c09d62d452f787674be17cc6caa062d2d76e8ea

Send DingTalk message core code

@Slf4j
@Service
public class DingMsgService {
    
    

    @Value("${config.dingtalk.secret}")
    private String dingtalkSecret;

    @Value("${config.dingtalk.webhook}")
    private String dingtalkWebhook;


    public void sendDingTalkMsg(String content) {
    
    

        // 钉钉最大只能发送2000个字符
        if (content.length() >= 1990) {
    
    
            content = content.substring(0, 1990);
        }

        DingTalkSendMsgRequestDTO requestDTO = new DingTalkSendMsgRequestDTO();
        requestDTO.setSecret(dingtalkSecret);
        requestDTO.setWebhook(dingtalkWebhook);
        requestDTO.setContent(content);

        //消息内容
        Map<String, String> contentMap = new HashMap<>();
        contentMap.put("content", requestDTO.getContent());
        //通知人
        Map<String, Object> atMap = new HashMap<>();
        //1.是否通知所有人
        atMap.put("isAtAll", requestDTO.getIsAtAll());
        //2.通知具体人的手机号码列表
        atMap.put("atMobiles", requestDTO.getMobileList());
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("msgtype", "text");
        reqMap.put("text", contentMap);
        reqMap.put("at", atMap);
        requestDTO.setContent(JSON.toJSONString(reqMap));

        try {
    
    
            String secret = requestDTO.getSecret();
            //获取系统时间戳
            long timestamp = Instant.now().toEpochMilli();
            //拼接
            String stringToSign = timestamp + "\n" + secret;
            //使用HmacSHA256算法计算签名
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
            //进行Base64 encode 得到最后的sign,可以拼接进url里
            String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
            //钉钉机器人地址(配置机器人的webhook)
            String dingUrl = requestDTO.getWebhook() + "&timestamp=" + timestamp + "&sign=" + sign;

            String result = HttpUtil.post(dingUrl, requestDTO.getContent());
            log.info("re={}", result);
        } catch (Exception e) {
    
    
            log.error("钉钉推送消息出现异常", e);
        }
    }
}

sample code

@RestController
public class TestController {
    
    

    @GetMapping(value = "test")
    public R test() {
    
    
        // 异常代码
        System.out.print(1 / 0);
        return R.ok();
    }
}

source address

other

  • When we usually develop interfaces, we encounter interface exceptions, and we hope to know as soon as possible
  • In the past experience, we have informed the corresponding personnel through emails and other means
  • Most alerts can now be sent to the relevant app
  • Group robot is an advanced extension function of DingTalk group. Group robot can aggregate the information of third-party services into the group chat to realize automatic information synchronization
  • With the help of DingTalk Robot, we can easily notify the corresponding personnel of abnormal alarm information by calling the official API

Guess you like

Origin blog.csdn.net/u010800804/article/details/130477842