spring boot 全局异常处理捕获数据脱敏异常的核心做法是自定义一个脱敏异常类,并在配置类中通过 @exceptionhandler 或 @controlleradvice 进行统一拦截。当业务逻辑检测到敏感数据需要脱敏但脱敏策略缺失、格式错误或执行失败时,抛出该自定义异常,全局处理器将其转换为标准的 json 错误响应(如 http 400 或 500),从而避免将原始堆栈信息暴露给前端。

如何定义并抛出脱敏异常
首先需要明确的是,脱敏通常是一个后置处理动作,但在某些场景下(如数据入库前校验、特定字段加密失败),它可能作为前置或同步步骤发生。为了捕获这些异常,必须定义一个继承自 RuntimeException 的自定义异常类,例如 SensitiveDataException。在业务代码中,当发现无法完成脱敏(例如正则表达式编译失败、密钥不可用)时,直接 throw 这个异常。这样做的目的是将脱敏逻辑与主业务流程解耦,确保任何脱敏相关的错误都能被上层统一感知。

package com.example.exception;
public class SensitiveDataException extends RuntimeException {
private String fieldName;
private String errorCode;
public SensitiveDataException(String fieldName, String message) {
super(message);
this.fieldName = fieldName;
this.errorCode = "DESENSITIZE_FAILED";
}
// Getters and Setters
public String getFieldName() { return fieldName; }
public String getErrorCode() { return errorCode; }
}
在 Service 层模拟抛出异常的代码如下:
public UserDTO processUser(UserDTO user) {
try {
// 模拟脱敏逻辑
if (user.getPhone() == null) {
throw new SensitiveDataException("phone", "Phone number is required for desensitization");
}
user.setPhone(desensitizePhone(user.getPhone()));
} catch (Exception e) {
// 捕获底层异常并包装为业务异常
throw new SensitiveDataException("phone", "Failed to desensitize phone: " + e.getMessage());
}
return user;
}
预期结果:当 processUser 接收到空手机号时,会抛出 SensitiveDataException,该异常会被后续的全局处理器捕获。
如何在全局控制器中统一处理该异常
定义好异常后,下一步是创建全局异常处理器。使用 @RestControllerAdvice 注解的类可以拦截所有 Controller 抛出的异常。在类中定义一个方法,并使用 @ExceptionHandler(SensitiveDataException.class) 指定处理目标。该方法应返回一个统一的响应体对象,包含错误码、消息和可能的字段名。这样做的好处是,无论脱敏异常发生在哪个 Controller,前端收到的都是结构一致的 JSON 数据,便于前端进行针对性的提示(如高亮显示具体哪个字段脱敏失败)。

package com.example.config;
import com.example.exception.SensitiveDataException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.HashMap;
import java.util.Map;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(SensitiveDataException.class)
public ResponseEntity<map object>> handleSensitiveDataException(SensitiveDataException ex) {
Map<string object> body = new HashMap();
body.put("success", false);
body.put("errorCode", ex.getErrorCode());
body.put("message", ex.getMessage());
body.put("field", ex.getFieldName());
return ResponseEntity.badRequest().body(body);
}
}</string></map>
预期结果:当上述 Service 层的异常被抛出并传播到 Controller 层时,handleSensitiveDataException 方法将被调用,返回 HTTP 400 状态码及包含详细错误信息的 JSON 响应。
脱敏异常处理对 API 响应结构的具体影响是什么
基于上述程序,当发生脱敏异常时,API 的响应结构会从正常的成功数据变为特定的错误结构。具体来说,HTTP 状态码变为 400 Bad Request,响应体是一个包含 success、errorCode、message 和 field 四个键的 JSON 对象。这种结构化的错误响应使得前端能够精确识别错误类型,并根据 field 字段定位到具体的表单输入项进行用户提示,而不是展示通用的服务器错误页面。此外,由于使用了 @RestControllerAdvice,这种处理方式不会影响其他非脱敏相关的异常处理流程,保持了系统的模块化。











