在 spring boot 中,全局异常处理与日志记录配合的核心做法是使用 @restcontrolleradvice 捕获所有未处理的异常,并在统一的方法内先通过 slf4j 记录详细堆栈,再返回标准化的错误响应。这样做既能保证前端获得清晰的 json 提示,又能让后端运维人员通过日志排查具体原因。需要注意的是,如果异常被其他拦截器或过滤器提前消费,或者配置了特定的错误页面跳转,全局处理器可能无法触发,因此必须确保异常能正确传播到 dispatcherservlet 的异常处理链中。

@ExceptionHandler 如何区分业务异常与系统异常
可以通过定义不同的异常类并分别编写处理逻辑来实现区分。对于预期的业务异常(如参数校验失败),通常只记录 WARN 级别日志并返回友好提示;对于意外的系统异常(如空指针、数据库连接断开),则记录 ERROR 级别日志并返回通用错误码。这种分层处理有助于快速定位问题严重程度。

import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@RestControllerAdvice
public class GlobalExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(BusinessException.class)
public ResponseEntity<result> handleBusinessException(BusinessException e) {
log.warn("业务异常: {}", e.getMessage());
return ResponseEntity.badRequest().body(Result.error(e.getCode(), e.getMessage()));
}
@ExceptionHandler(Exception.class)
public ResponseEntity<result> handleException(Exception e) {
log.error("系统内部错误", e);
return ResponseEntity.status(500).body(Result.error(500, "服务器繁忙"));
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
class Result {
private int code;
private String message;
public static Result error(int code, String msg) { return new Result(code, msg); }
}
// 自定义业务异常
public class BusinessException extends RuntimeException {
private int code;
public BusinessException(int code, String msg) { super(msg); this.code = code; }
public int getCode() { return code; }
}</result></result>
日志格式如何包含请求上下文信息
为了在海量日志中快速关联异常与具体请求,需要利用 ThreadLocal 或 MDC(Mapped Diagnostic Context)将请求 ID、用户 ID 等关键信息注入到日志上下文中。这样在查看异常堆栈时,可以直接看到是哪个请求导致了错误,无需反复翻阅代码追踪链路。

import org.springframework.stereotype.Component;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.MDC;
import java.util.UUID;
@Aspect
@Component
public class LogMdcAspect {
@Around("execution(* com.example.controller..*.*(..))")
public Object addTraceId(ProceedingJoinPoint joinPoint) throws Throwable {
String traceId = UUID.randomUUID().toString();
try {
MDC.put("traceId", traceId);
return joinPoint.proceed();
} finally {
MDC.clear();
}
}
}
当 try-catch 包裹异常时全局处理会失效吗
是的,如果在 Controller 方法内部使用了 try-catch 吞掉了异常,全局异常处理器将无法捕获该异常。此时需要在 catch 块中手动记录日志,或者重新抛出异常以触发全局处理逻辑。最佳实践是避免在 Controller 层过度使用 try-catch,而是依赖 AOP 或全局处理器进行统一管控。











