在Spring Boot中集成企业微信API的统一异常处理与日志追踪方案

在Spring Boot中集成企业微信API的统一异常处理与日志追踪方案

企业微信(WeCom)API调用过程中可能因网络波动、权限不足、参数错误或频率限制等原因抛出异常。若未进行统一处理,将导致接口返回格式不一致、错误信息暴露敏感细节,且难以排查问题。本文基于Spring Boot,结合@ControllerAdvice、MDC日志上下文和企业微信官方SDK,构建一套结构清晰、可追溯、安全合规的异常处理与日志追踪体系。

1. 自定义企业微信异常类型

首先定义业务相关的异常类,区分不同错误场景:

java 复制代码
package wlkankan.cn.exception;

public class WecomApiException extends RuntimeException {
    private final int errcode;
    private final String errmsg;

    public WecomApiException(int errcode, String errmsg) {
        super("Wecom API error: " + errmsg + " (code=" + errcode + ")");
        this.errcode = errcode;
        this.errmsg = errmsg;
    }

    public int getErrcode() { return errcode; }
    public String getErrmsg() { return errmsg; }
}

2. 全局异常处理器

使用@ControllerAdvice捕获所有控制器异常,并返回标准化JSON响应:

java 复制代码
package wlkankan.cn.handler;

import wlkankan.cn.exception.WecomApiError;
import wlkankan.cn.exception.WecomApiException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.UUID;

@RestControllerAdvice
public class GlobalWecomExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalWecomExceptionHandler.class);

    @ExceptionHandler(WecomApiException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ErrorResponse handleWecomApiException(WecomApiException ex) {
        String traceId = MdcUtil.getTraceId();
        log.warn("Wecom API call failed [traceId={}], errcode={}, errmsg={}",
                traceId, ex.getErrcode(), ex.getErrmsg());

        return new ErrorResponse(traceId, "WECHAT_API_ERROR", ex.getErrmsg());
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ErrorResponse handleUnexpectedException(Exception ex) {
        String traceId = MdcUtil.getTraceId();
        log.error("Unexpected error in wecom service [traceId={}]", traceId, ex);
        return new ErrorResponse(traceId, "INTERNAL_ERROR", "系统内部错误");
    }

    public static class ErrorResponse {
        private final String traceId;
        private final String code;
        private final String message;

        public ErrorResponse(String traceId, String code, String message) {
            this.traceId = traceId;
            this.code = code;
            this.message = message;
        }

        // getters
    }
}

3. 请求级唯一追踪ID(Trace ID)

通过拦截器生成并注入traceId到MDC(Mapped Diagnostic Context),确保日志可串联:

java 复制代码
package wlkankan.cn.log;

import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Component
public class TraceIdInterceptor implements HandlerInterceptor {
    private static final String TRACE_ID_HEADER = "X-Trace-ID";
    public static final String TRACE_ID_MDC_KEY = "traceId";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String traceId = request.getHeader(TRACE_ID_HEADER);
        if (traceId == null || traceId.isEmpty()) {
            traceId = UUID.randomUUID().toString().replace("-", "");
        }
        MDC.put(TRACE_ID_MDC_KEY, traceId);
        response.setHeader(TRACE_ID_HEADER, traceId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        MDC.clear();
    }
}

配套工具类:

java 复制代码
package wlkankan.cn.log;

public class MdcUtil {
    public static String getTraceId() {
        return org.slf4j.MDC.get(TraceIdInterceptor.TRACE_ID_MDC_KEY);
    }
}

4. 企业微信API调用封装与异常转换

在调用企业微信SDK时,主动捕获底层异常并转换为自定义异常:

java 复制代码
package wlkankan.cn.wecom;

import com.tencent.wework.api.WxClient;
import com.tencent.wework.api.model.SendResult;
import wlkankan.cn.exception.WecomApiException;
import wlkankan.cn.log.MdcUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WecomMessageService {
    private static final Logger log = LoggerFactory.getLogger(WecomMessageService.class);
    private final WxClient wxClient;

    public void sendTextMessage(String userId, String content) {
        String traceId = MdcUtil.getTraceId();
        try {
            SendResult result = wxClient.sendMessage(userId, content);
            if (!"0".equals(result.getErrcode())) {
                throw new WecomApiException(Integer.parseInt(result.getErrcode()), result.getErrmsg());
            }
            log.info("Wecom message sent successfully [traceId={}, to={}]", traceId, userId);
        } catch (RuntimeException e) {
            if (e instanceof WecomApiException) throw e;
            // 转换第三方SDK异常
            log.error("Failed to send wecom message [traceId={}]", traceId, e);
            throw new WecomApiException(-1, "企业微信服务调用异常");
        }
    }
}

5. 日志配置(logback-spring.xml)

在日志输出中包含traceId字段:

xml 复制代码
<configuration>
  <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level [%X{traceId}] %logger{36} - %msg%n</pattern>
    </encoder>
  </appender>
  <root level="INFO">
    <appender-ref ref="CONSOLE"/>
  </root>
</configuration>

通过上述设计,所有企业微信API调用均具备统一的错误响应格式、完整的请求链路追踪能力及结构化日志输出,极大提升系统可观测性与运维效率。

相关推荐
gelald3 分钟前
Spring Boot - 自动配置原理
java·spring boot·后端
希望永不加班16 分钟前
SpringBoot 集成测试:@SpringBootTest 与 MockMvc
java·spring boot·后端·log4j·集成测试
计算机学姐1 小时前
基于SpringBoot的高校竞赛管理系统
java·spring boot·后端·spring·信息可视化·tomcat·mybatis
leo_messi941 小时前
RabbitMq(五) -- SpringBoot整合 RabbitMQ 完整实现
spring boot·rabbitmq·java-rabbitmq
huanmieyaoseng10031 小时前
SpringBoot使用Redis缓存
java·spring boot·后端
QC·Rex1 小时前
Spring Boot + Spring AI 实战:从零构建企业级 AI 应用
spring boot·大模型·向量数据库·rag·spring ai·tool calling
白露与泡影2 小时前
Spring Boot 缓存架构:一行配置切换 Caffeine 与 Redis,透明支持多租户隔离
spring boot·缓存·架构
indexsunny3 小时前
互联网大厂Java面试实战:从Spring Boot到微服务架构的技术问答
java·spring boot·redis·微服务·面试·kafka·spring security
计算机学姐3 小时前
基于SpringBoot的在线学习网站平台【个性化推荐+数据可视化+课程章节学习】
java·vue.js·spring boot·后端·学习·mysql·信息可视化
星晨雪海3 小时前
Spring Boot 常用注解
java·spring boot·后端