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

目標(biāo):構(gòu)建一套健壯的全局異常處理方案,統(tǒng)一錯(cuò)誤響應(yīng)、可追蹤的日志(requestId/MDC),并把異常上報(bào)為監(jiān)控指標(biāo)(使用 Micrometer),方便在生產(chǎn)環(huán)境定位與統(tǒng)計(jì)異常。
1. 背景與目標(biāo)
生產(chǎn)環(huán)境中,異常無(wú)處不在。我們要解決三件事:
- 對(duì)外統(tǒng)一 JSON 錯(cuò)誤格式,便于前端/客戶端解析與展示;
- 在日志中攜帶可追溯的
requestId(MDC),便于從日志中串聯(lián)一條請(qǐng)求的全部操作; - 對(duì)異常做指標(biāo)統(tǒng)計(jì)(例如按異常類型/狀態(tài)碼計(jì)數(shù)),能在監(jiān)控平臺(tái)(Prometheus/Grafana)上報(bào)警與分析。
2. 設(shè)計(jì)思路(要點(diǎn))
- 使用
@RestControllerAdvice+@ExceptionHandler進(jìn)行全局捕獲; - 返回標(biāo)準(zhǔn)
ErrorResponse(包含時(shí)間戳、HTTP 狀態(tài)碼、業(yè)務(wù)錯(cuò)誤碼、message、path、requestId); - 在異常處理器里同時(shí)
log.error(...)并把異常計(jì)數(shù)交給MeterRegistry(Micrometer); - 通過(guò)
OncePerRequestFilter在每個(gè)請(qǐng)求開(kāi)始時(shí)生成requestId并放入 SLF4J 的 MDC(MDC.put("requestId", id)); - 配置
logback-spring.xml把%X{requestId}輸出到日志 pattern,建議也輸出 JSON(視需求)。
3. 項(xiàng)目依賴(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. 通用錯(cuò)誤響應(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; // 可選擴(kuò)展字段
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. 全局異常處理實(shí)現(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;
// 一個(gè)簡(jiǎn)單的異常計(jì)數(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)控計(jì)數(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ù)校驗(yàn)異常
@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);
// 總量計(jì)數(shù)
genericExceptionCounter.increment();
// 按異常類計(jì)數(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ù)器繁忙,請(qǐng)稍后重試",
request.getRequestURI(),
requestId
);
// 在開(kāi)發(fā)環(huán)境可以把 ex.getMessage() 或堆棧信息放到 details 中(生產(chǎn)環(huán)境慎用)
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(err);
}
}說(shuō)明:
- 在處理器中我們同時(shí)
log和meterRegistry.counter(...).increment(),用于日志與監(jiān)控; MDC.get("requestId")用于把請(qǐng)求的 requestId 寫入返回體,方便客戶端帶回查日志。
7. 請(qǐng)求 ID 與 MDC 過(guò)濾器(保證每條請(qǐng)求都有 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);
// 同時(shí)將 requestId 放回響應(yīng)頭,便于前端或網(wǎng)關(guān)追蹤
response.setHeader(REQUEST_ID_HEADER, requestId);
filterChain.doFilter(request, response);
} finally {
MDC.remove("requestId");
}
}
}說(shuō)明:
- 每次請(qǐng)求都會(huì)生成(或沿用上游)
X-Request-Id,并放到 MDC,日志 pattern 能輸出%X{requestId}; - 響應(yīng)中返回該 header,有利于客戶端/運(yùn)維串聯(lián)。
8. 日志配置與示例輸出
application.properties(關(guān)鍵項(xiàng))
# 暴露 Actuator prometheus 端點(diǎn) management.endpoints.web.exposure.include=health,info,prometheus,metrics management.endpoint.prometheus.enabled=true # 日志級(jí)別(根據(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>日志示例(一條報(bào)錯(cuò)請(qǐng)求)
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)
...你會(huì)看到 requestId 出現(xiàn)在每條日志,便于用 grep 或日志平臺(tái)(ELK/EFK)按 requestId 過(guò)濾整條調(diào)用鏈。
9. 將異常計(jì)數(shù)暴露到監(jiān)控(Actuator + Micrometer)
前文 GlobalExceptionHandler 已經(jīng)把計(jì)數(shù)器注冊(cè)到 Micrometer:
exceptions.totalexceptions.by_code{code=...}exceptions.by_type{type=...}
在 Prometheus 中抓取 Spring Boot 的 /actuator/prometheus 指標(biāo),就能在 Grafana 中根據(jù) exceptions.by_type 做報(bào)警規(guī)則。例如:如果 exceptions.by_type{type="NullPointerException"} 在 5 分鐘內(nèi)增幅過(guò)大,就觸發(fā)報(bào)警。
10. 常見(jiàn)場(chǎng)景與處理建議
- 參數(shù)校驗(yàn)失?。?code>MethodArgumentNotValidException)
- 建議把字段錯(cuò)誤拼成單行 message(示例中已實(shí)現(xiàn)),并返回 400。
- 業(yè)務(wù)異常(自定義
BusinessException)- 業(yè)務(wù)異??蓴y帶
code,前端可根據(jù) code 做差異化提示或重試策略;監(jiān)控中也可以以code為標(biāo)簽統(tǒng)計(jì)。
- 業(yè)務(wù)異??蓴y帶
- 第三方超時(shí)/HTTP 錯(cuò)誤(RestTemplate/WebClient)
- 在調(diào)用處拋出有意義的自定義異?;?qū)⒃惓0b后拋出;在全局異常處理器中根據(jù)異常類型映射為 502/504 等狀態(tài),并計(jì)數(shù)。
- 鏈路追蹤(可選)
- 若有分布式追蹤需求,可接入 OpenTelemetry/Zipkin/Jaeger,但仍保留
requestId做本地快速查找。
- 若有分布式追蹤需求,可接入 OpenTelemetry/Zipkin/Jaeger,但仍保留
- 安全注意
- 生產(chǎn)環(huán)境不要在 API 返回中包含完整堆?;蛎舾凶侄危ㄊ纠袃H返回通用 message)??梢栽陂_(kāi)發(fā) profile 下增加
details。
- 生產(chǎn)環(huán)境不要在 API 返回中包含完整堆?;蛎舾凶侄危ㄊ纠袃H返回通用 message)??梢栽陂_(kāi)發(fā) profile 下增加
11. 小結(jié)與部署建議
- 統(tǒng)一異常處理 可以顯著提升前后端協(xié)作效率與錯(cuò)誤可觀察性;
- MDC + requestId 是生產(chǎn)排查的第一要素,務(wù)必保證上游(網(wǎng)關(guān))能傳遞
X-Request-Id,否則服務(wù)端生成并回傳; - 監(jiān)控計(jì)數(shù)(Micrometer)使異常不再是“偶發(fā)的黑盒”,可以在 Grafana/Prometheus 上設(shè)定閾值與報(bào)警;
- 日志集中化 建議配合 ELK/EFK(或云日志)保存結(jié)構(gòu)化日志(JSON)以便于按
requestId、code、type聚合查詢; - 對(duì)外返回 應(yīng)保持穩(wěn)定的 JSON 格式與明確的狀態(tài)碼,避免泄露內(nèi)部實(shí)現(xiàn)細(xì)節(jié)。
相關(guān)文章
使用Feign遠(yuǎn)程調(diào)用時(shí),序列化對(duì)象失敗的解決
這篇文章主要介紹了使用Feign遠(yuǎn)程調(diào)用時(shí),序列化對(duì)象失敗的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07
MyBatis實(shí)現(xiàn)多表聯(lián)查的詳細(xì)代碼
這篇文章主要介紹了MyBatis如何實(shí)現(xiàn)多表聯(lián)查,通過(guò)實(shí)例代碼給大家介紹使用映射配置文件實(shí)現(xiàn)多表聯(lián)查,使用注解的方式實(shí)現(xiàn)多表聯(lián)查,需要的朋友可以參考下2022-08-08
Java?Spring?boot實(shí)現(xiàn)生成二維碼
大家好,本篇文章主要講的是Java?Spring?boot實(shí)現(xiàn)生成二維碼,感興趣的同學(xué)趕快來(lái)看一看吧,對(duì)你有幫助的話記得收藏一下2022-02-02
Spring項(xiàng)目中Ordered接口的應(yīng)用之全局過(guò)濾器(GlobalFilter)的順序控制
在Spring框架,尤其是Spring Cloud Gateway或Spring WebFlux項(xiàng)目中,Ordered接口扮演著重要的角色,特別是在實(shí)現(xiàn)全局過(guò)濾器(GlobalFilter)時(shí),用于控制過(guò)濾器執(zhí)行的優(yōu)先級(jí),下面將介紹如何在Spring項(xiàng)目中使用Ordered接口來(lái)管理Global Filter的執(zhí)行順序,需要的朋友可以參考下2024-06-06
idea打開(kāi)運(yùn)行配置java?web項(xiàng)目的全過(guò)程
這篇文章主要給大家介紹了關(guān)于idea打開(kāi)運(yùn)行配置java?web項(xiàng)目的相關(guān)資料,有些時(shí)候我們用IDEA跑之前用eclipse中運(yùn)行的項(xiàng)目的時(shí)候,總是不止所措,要不就是只展示html,要不就是不能部署成功,需要的朋友可以參考下2023-08-08
mybatis動(dòng)態(tài)新增(insert)和修改(update)方式
這篇文章主要介紹了mybatis動(dòng)態(tài)新增(insert)和修改(update)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05
利用微信小程序+JAVA實(shí)現(xiàn)微信支付的全過(guò)程
微信支付是一種在線支付解決方案,允許用戶通過(guò)微信內(nèi)的支付功能進(jìn)行付款,下面這篇文章主要給大家介紹了關(guān)于利用微信小程序+JAVA實(shí)現(xiàn)微信支付的相關(guān)資料,需要的朋友可以參考下2024-08-08
總結(jié)Java中線程的狀態(tài)及多線程的實(shí)現(xiàn)方式
Java中可以通過(guò)Thread類和Runnable接口來(lái)創(chuàng)建多個(gè)線程,線程擁有五種狀態(tài),下面我們就來(lái)簡(jiǎn)單總結(jié)Java中線程的狀態(tài)及多線程的實(shí)現(xiàn)方式:2016-07-07

