Spring Boot全局異常處理與日志監(jiān)控全解析
代碼以 Spring Boot 3 / Java 17 風(fēng)格示例(可適配 Spring Boot 2.x 做少量改動)

目標(biāo):構(gòu)建一套健壯的全局異常處理方案,統(tǒng)一錯誤響應(yīng)、可追蹤的日志(requestId/MDC),并把異常上報為監(jiān)控指標(biāo)(使用 Micrometer),方便在生產(chǎn)環(huán)境定位與統(tǒng)計異常。
1. 背景與目標(biāo)
生產(chǎn)環(huán)境中,異常無處不在。我們要解決三件事:
- 對外統(tǒng)一 JSON 錯誤格式,便于前端/客戶端解析與展示;
- 在日志中攜帶可追溯的
requestId(MDC),便于從日志中串聯(lián)一條請求的全部操作; - 對異常做指標(biāo)統(tǒng)計(例如按異常類型/狀態(tài)碼計數(shù)),能在監(jiān)控平臺(Prometheus/Grafana)上報警與分析。
2. 設(shè)計思路(要點)
- 使用
@RestControllerAdvice+@ExceptionHandler進行全局捕獲; - 返回標(biāo)準(zhǔn)
ErrorResponse(包含時間戳、HTTP 狀態(tài)碼、業(yè)務(wù)錯誤碼、message、path、requestId); - 在異常處理器里同時
log.error(...)并把異常計數(shù)交給MeterRegistry(Micrometer); - 通過
OncePerRequestFilter在每個請求開始時生成requestId并放入 SLF4J 的 MDC(MDC.put("requestId", id)); - 配置
logback-spring.xml把%X{requestId}輸出到日志 pattern,建議也輸出 JSON(視需求)。
3. 項目依賴(Maven)
<!-- pom.xml 依賴片段 -->
<dependencies>
<!-- Spring Boot Starter Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 日志 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</dependency>
<!-- Validation -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!-- Actuator & Micrometer (Prometheus) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
</dependencies>4. 通用錯誤響應(yīng) DTO
src/main/java/com/example/demo/api/ErrorResponse.java
package com.example.demo.api;
import java.time.Instant;
import java.util.Map;
public class ErrorResponse {
private Instant timestamp;
private int status;
private String error;
private String message;
private String path;
private String requestId;
private Map<String, Object> details; // 可選擴展字段
public ErrorResponse() {}
public ErrorResponse(int status, String error, String message, String path, String requestId) {
this.timestamp = Instant.now();
this.status = status;
this.error = error;
this.message = message;
this.path = path;
this.requestId = requestId;
}
// getters & setters omitted for brevity
}5. 自定義業(yè)務(wù)異常示例
src/main/java/com/example/demo/exception/BusinessException.java
package com.example.demo.exception;
public class BusinessException extends RuntimeException {
private final String code;
public BusinessException(String code, String message) {
super(message);
this.code = code;
}
public String getCode() {
return code;
}
}6. 全局異常處理實現(xiàn)(日志 + 指標(biāo))
src/main/java/com/example/demo/exception/GlobalExceptionHandler.java
package com.example.demo.exception;
import com.example.demo.api.ErrorResponse;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Counter;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.stream.Collectors;
@RestControllerAdvice
public class GlobalExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
private final MeterRegistry meterRegistry;
// 一個簡單的異常計數(shù)器前綴(可按異常 class、path、status 維度構(gòu)造標(biāo)簽)
private final Counter genericExceptionCounter;
public GlobalExceptionHandler(MeterRegistry meterRegistry) {
this.meterRegistry = meterRegistry;
this.genericExceptionCounter = Counter.builder("exceptions.total")
.description("Total number of handled exceptions")
.register(meterRegistry);
}
// 業(yè)務(wù)異常處理
@ExceptionHandler(BusinessException.class)
public ResponseEntity<ErrorResponse> handleBusiness(BusinessException ex, HttpServletRequest request) {
String requestId = MDC.get("requestId");
log.warn("BusinessException - requestId={}, path={}, code={}, msg={}",
requestId, request.getRequestURI(), ex.getCode(), ex.getMessage());
// 增加監(jiān)控計數(shù)(按業(yè)務(wù)碼)
meterRegistry.counter("exceptions.by_code", "code", ex.getCode()).increment();
ErrorResponse err = new ErrorResponse(
HttpStatus.BAD_REQUEST.value(),
"Business Error",
ex.getMessage(),
request.getRequestURI(),
requestId
);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(err);
}
// 參數(shù)校驗異常
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ErrorResponse> handleValidation(MethodArgumentNotValidException ex, HttpServletRequest request) {
String requestId = MDC.get("requestId");
String msg = ex.getBindingResult().getFieldErrors().stream()
.map(fe -> fe.getField() + ":" + fe.getDefaultMessage())
.collect(Collectors.joining("; "));
log.info("Validation failed - requestId={}, path={}, errors={}", requestId, request.getRequestURI(), msg);
meterRegistry.counter("exceptions.validation").increment();
ErrorResponse err = new ErrorResponse(
HttpStatus.BAD_REQUEST.value(),
"Validation Error",
msg,
request.getRequestURI(),
requestId
);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(err);
}
// 通用異常處理
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleGeneric(Exception ex, HttpServletRequest request) {
String requestId = MDC.get("requestId");
log.error("Unhandled exception - requestId={}, path={}", requestId, request.getRequestURI(), ex);
// 總量計數(shù)
genericExceptionCounter.increment();
// 按異常類計數(shù)標(biāo)簽
meterRegistry.counter("exceptions.by_type", "type", ex.getClass().getSimpleName()).increment();
ErrorResponse err = new ErrorResponse(
HttpStatus.INTERNAL_SERVER_ERROR.value(),
"Internal Server Error",
"服務(wù)器繁忙,請稍后重試",
request.getRequestURI(),
requestId
);
// 在開發(fā)環(huán)境可以把 ex.getMessage() 或堆棧信息放到 details 中(生產(chǎn)環(huán)境慎用)
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(err);
}
}說明:
- 在處理器中我們同時
log和meterRegistry.counter(...).increment(),用于日志與監(jiān)控; MDC.get("requestId")用于把請求的 requestId 寫入返回體,方便客戶端帶回查日志。
7. 請求 ID 與 MDC 過濾器(保證每條請求都有 requestId)
src/main/java/com/example/demo/filter/RequestIdFilter.java
package com.example.demo.filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
import java.util.UUID;
@Component
public class RequestIdFilter extends OncePerRequestFilter {
private static final String REQUEST_ID_HEADER = "X-Request-Id";
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
try {
String requestId = request.getHeader(REQUEST_ID_HEADER);
if (requestId == null || requestId.isBlank()) {
requestId = UUID.randomUUID().toString();
}
MDC.put("requestId", requestId);
// 同時將 requestId 放回響應(yīng)頭,便于前端或網(wǎng)關(guān)追蹤
response.setHeader(REQUEST_ID_HEADER, requestId);
filterChain.doFilter(request, response);
} finally {
MDC.remove("requestId");
}
}
}說明:
- 每次請求都會生成(或沿用上游)
X-Request-Id,并放到 MDC,日志 pattern 能輸出%X{requestId}; - 響應(yīng)中返回該 header,有利于客戶端/運維串聯(lián)。
8. 日志配置與示例輸出
application.properties(關(guān)鍵項)
# 暴露 Actuator prometheus 端點 management.endpoints.web.exposure.include=health,info,prometheus,metrics management.endpoint.prometheus.enabled=true # 日志級別(根據(jù)環(huán)境調(diào)整) logging.level.root=INFO logging.level.com.example=DEBUG
logback-spring.xml(pattern 示例)
放在 src/main/resources/logback-spring.xml:
<configuration>
<springProfile name="prod">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<!-- 輸出包含 requestId -->
<pattern>%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX} [%thread] %-5level %logger{36} - %msg - requestId=%X{requestId}%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT"/>
</root>
</springProfile>
<springProfile name="!prod">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg - requestId=%X{requestId}%n</pattern>
</encoder>
</appender>
<root level="DEBUG">
<appender-ref ref="STDOUT"/>
</root>
</springProfile>
</configuration>日志示例(一條報錯請求)
2025-08-10T18:34:10.123+03:00 [http-nio-8080-exec-1] ERROR com.example.demo.exception.GlobalExceptionHandler - Unhandled exception - requestId=2f1a8c7f-1d2b-4f0a-9b2a-123456789abc, path=/api/orders
java.lang.NullPointerException: ...
at com.example.demo.service.OrderService.create(OrderService.java:45)
...你會看到 requestId 出現(xiàn)在每條日志,便于用 grep 或日志平臺(ELK/EFK)按 requestId 過濾整條調(diào)用鏈。
9. 將異常計數(shù)暴露到監(jiān)控(Actuator + Micrometer)
前文 GlobalExceptionHandler 已經(jīng)把計數(shù)器注冊到 Micrometer:
exceptions.totalexceptions.by_code{code=...}exceptions.by_type{type=...}
在 Prometheus 中抓取 Spring Boot 的 /actuator/prometheus 指標(biāo),就能在 Grafana 中根據(jù) exceptions.by_type 做報警規(guī)則。例如:如果 exceptions.by_type{type="NullPointerException"} 在 5 分鐘內(nèi)增幅過大,就觸發(fā)報警。
10. 常見場景與處理建議
- 參數(shù)校驗失?。?code>MethodArgumentNotValidException)
- 建議把字段錯誤拼成單行 message(示例中已實現(xiàn)),并返回 400。
- 業(yè)務(wù)異常(自定義
BusinessException)- 業(yè)務(wù)異??蓴y帶
code,前端可根據(jù) code 做差異化提示或重試策略;監(jiān)控中也可以以code為標(biāo)簽統(tǒng)計。
- 業(yè)務(wù)異??蓴y帶
- 第三方超時/HTTP 錯誤(RestTemplate/WebClient)
- 在調(diào)用處拋出有意義的自定義異常或?qū)⒃惓0b后拋出;在全局異常處理器中根據(jù)異常類型映射為 502/504 等狀態(tài),并計數(shù)。
- 鏈路追蹤(可選)
- 若有分布式追蹤需求,可接入 OpenTelemetry/Zipkin/Jaeger,但仍保留
requestId做本地快速查找。
- 若有分布式追蹤需求,可接入 OpenTelemetry/Zipkin/Jaeger,但仍保留
- 安全注意
- 生產(chǎn)環(huán)境不要在 API 返回中包含完整堆?;蛎舾凶侄危ㄊ纠袃H返回通用 message)??梢栽陂_發(fā) profile 下增加
details。
- 生產(chǎn)環(huán)境不要在 API 返回中包含完整堆?;蛎舾凶侄危ㄊ纠袃H返回通用 message)??梢栽陂_發(fā) profile 下增加
11. 小結(jié)與部署建議
- 統(tǒng)一異常處理 可以顯著提升前后端協(xié)作效率與錯誤可觀察性;
- MDC + requestId 是生產(chǎn)排查的第一要素,務(wù)必保證上游(網(wǎng)關(guān))能傳遞
X-Request-Id,否則服務(wù)端生成并回傳; - 監(jiān)控計數(shù)(Micrometer)使異常不再是“偶發(fā)的黑盒”,可以在 Grafana/Prometheus 上設(shè)定閾值與報警;
- 日志集中化 建議配合 ELK/EFK(或云日志)保存結(jié)構(gòu)化日志(JSON)以便于按
requestId、code、type聚合查詢; - 對外返回 應(yīng)保持穩(wěn)定的 JSON 格式與明確的狀態(tài)碼,避免泄露內(nèi)部實現(xiàn)細(xì)節(jié)。
相關(guān)文章
使用Feign遠(yuǎn)程調(diào)用時,序列化對象失敗的解決
這篇文章主要介紹了使用Feign遠(yuǎn)程調(diào)用時,序列化對象失敗的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07
MyBatis實現(xiàn)多表聯(lián)查的詳細(xì)代碼
這篇文章主要介紹了MyBatis如何實現(xiàn)多表聯(lián)查,通過實例代碼給大家介紹使用映射配置文件實現(xiàn)多表聯(lián)查,使用注解的方式實現(xiàn)多表聯(lián)查,需要的朋友可以參考下2022-08-08
Spring項目中Ordered接口的應(yīng)用之全局過濾器(GlobalFilter)的順序控制
在Spring框架,尤其是Spring Cloud Gateway或Spring WebFlux項目中,Ordered接口扮演著重要的角色,特別是在實現(xiàn)全局過濾器(GlobalFilter)時,用于控制過濾器執(zhí)行的優(yōu)先級,下面將介紹如何在Spring項目中使用Ordered接口來管理Global Filter的執(zhí)行順序,需要的朋友可以參考下2024-06-06
mybatis動態(tài)新增(insert)和修改(update)方式
這篇文章主要介紹了mybatis動態(tài)新增(insert)和修改(update)方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05
總結(jié)Java中線程的狀態(tài)及多線程的實現(xiàn)方式
Java中可以通過Thread類和Runnable接口來創(chuàng)建多個線程,線程擁有五種狀態(tài),下面我們就來簡單總結(jié)Java中線程的狀態(tài)及多線程的實現(xiàn)方式:2016-07-07

