feat: 优化钉钉消息模板渲染逻辑,增加异常处理和日志记录

This commit is contained in:
2025-02-10 22:05:59 +08:00
parent f1df944b08
commit ebf3ee061f

View File

@@ -16,6 +16,8 @@ import cn.lihongjie.coal.exception.BizException;
import com.fasterxml.jackson.databind.ObjectMapper;
import freemarker.core.InvalidReferenceException;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
@@ -116,29 +118,44 @@ public class DingtalkBotService extends BaseService<DingtalkBotEntity, DingtalkB
HashMap<Object, Object> body = new HashMap<>();
body.put("msgtype", "markdown");
body.put(
"markdown",
new HashMap<String, Object>() {
{
put(
"title",
FreeMakerUtils.render(
dingtalkBotTemplateEntity.getTitle(), params));
put(
"text",
FreeMakerUtils.render(
dingtalkBotTemplateEntity.getTemplate(), params));
}
});
try {
String content = FreeMakerUtils.render(dingtalkBotTemplateEntity.getTemplate(), params);
String title = FreeMakerUtils.render(dingtalkBotTemplateEntity.getTitle(), params);
body.put(
"markdown",
new HashMap<String, Object>() {
{
put("title", title);
put("text", content);
}
});
} catch (Exception referenceException) {
if (referenceException instanceof InvalidReferenceException ee) {
log.info(
"模板渲染失败, 模板: {} 参数: {} 表达式:{}",
dingtalkBotTemplateEntity,
params,
ee.getBlamedExpressionString(),
referenceException);
throw new BizException("模板渲染失败, 请检查模板参数是否正确 " + ee.getBlamedExpressionString());
} else {
throw referenceException;
}
}
try {
String postBody = objectMapper.writeValueAsString(body);
String response =
HttpUtil.post(
dingtalkBotEntity.getUrl(), postBody);
String response = HttpUtil.post(dingtalkBotEntity.getUrl(), postBody);
log.info("发送钉钉消息成功, 请求: {} 返回结果: {} ", postBody , response);
log.info("发送钉钉消息成功, 请求: {} 返回结果: {} ", postBody, response);
sendMsgResult.setResponse(response);