使用 spring aop 统一记录异常日志,核心做法是定义一个切面类,利用 @afterthrowing 注解拦截目标方法抛出的异常,在通知方法中获取异常对象和请求信息并写入日志。这样可以在不侵入业务代码的前提下,集中处理所有未捕获的异常,确保关键错误被持久化记录。

如何定义切面并配置切入点
定义切面的关键是创建带有 @Aspect 注解的组件,并使用 @Pointcut 指定需要拦截的方法范围,例如所有 Controller 层的方法。通过 @AfterThrowing 将切点与异常处理逻辑绑定,当目标方法抛出异常时,Spring 会自动调用通知方法。配置时需确保切面类的 Bean 被 Spring 容器管理,且开启了 AspectJ 自动代理支持。

import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; @Aspect @Component public class ExceptionLogAspect { @Pointcut("execution(* com.example.controller..*(..))") public void controllerLayer() {} @AfterThrowing(pointcut = "controllerLayer()", throwing = "ex") public void logException(Exception ex) { System.out.println("Caught exception: " + ex.getMessage()); } }
如何在通知中获取请求上下文信息
在通知方法中获取请求上下文(如 URL、参数)通常借助 RequestAttributes 或 JoinPoint 对象。通过 JoinPoint 可以获取方法签名和参数值,而通过 RequestContextHolder 可以访问当前 HTTP 请求。将这些信息与异常堆栈结合,能提供更完整的排查线索。注意需在非 Web 环境下处理空指针风险。

import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Aspect; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; @Aspect @Component public class DetailedExceptionLogAspect { @AfterThrowing(pointcut = "execution(* com.example.controller..*(..))", throwing = "ex") public void logDetailedException(JoinPoint joinPoint, Exception ex) { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); if (attributes != null) { String url = attributes.getRequest().getRequestURI(); System.out.println("URL: " + url + ", Exception: " + ex.getMessage()); } else { System.out.println("Non-web context, Exception: " + ex.getMessage()); } } }
如何处理自定义业务异常以区分系统错误
对于自定义业务异常(如 BusinessException),可以通过在 @AfterThrowing 中判断异常类型来区分系统级错误和业务级提示。若为业务异常,可记录警告级别日志而不触发告警;若为系统异常,则记录错误级别并可能发送通知。这种分类处理有助于减少噪音,聚焦真正的问题。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











