spring boot 全局异常处理捕获 jpa 实体异常,核心在于利用 @controlleradvice 配合 @exceptionhandler 拦截 org.springframework.dao.dataintegrityviolationexception。当 jpa 执行持久化操作违反数据库约束(如唯一键冲突、非空限制)时,底层会抛出此异常,全局处理器将其转换为统一的 json 响应或错误页面,从而避免应用崩溃并向前端返回明确的业务错误信息。

DataIntegrityViolationException 的触发条件是什么
该异常通常在调用 save() 或 flush() 方法时触发,主要源于数据库层面的约束违规。最常见的场景包括插入重复的唯一键值、向非空字段传入 null 值,或者外键引用了不存在的数据。此时 Hibernate 会将底层的 SQL 异常包装为 DataIntegrityViolationException,开发者可以通过检查其内部的 Cause 来获取具体的 SQL 错误码或消息,进而判断是哪种类型的实体约束被破坏。

package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
interface UserRepository extends JpaRepository<user long> {
}
class User {
private Long id;
private String username;
// 省略 getter/setter
}</user>
如何在全局处理器中区分不同的约束类型
在 @ExceptionHandler 方法中,通过遍历 DataIntegrityViolationException 的嵌套异常链,可以定位到具体的 SQLException。不同数据库(如 MySQL、PostgreSQL)的错误码不同,但通常都能识别出“Duplicate entry”或“NotNullViolation”等关键字。根据这些关键字,可以在处理器中构建不同的业务逻辑,例如针对唯一键冲突返回“用户已存在”,针对非空约束返回“必填项缺失”,从而实现精细化的错误反馈。

package com.example.demo;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.dao.DataIntegrityViolationException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(DataIntegrityViolationException.class)
public ResponseEntity<map object>> handleDataIntegrityViolation(
DataIntegrityViolationException ex) {
Map<string object> errorBody = new HashMap();
Throwable cause = ex.getCause();
if (cause instanceof SQLException) {
String sqlState = ((SQLException) cause).getSQLState();
String message = cause.getMessage();
if (message != null && message.contains("Duplicate entry")) {
errorBody.put("error", "UNIQUE_CONSTRAINT_VIOLATION");
errorBody.put("message", "数据已存在");
} else if (sqlState != null && sqlState.startsWith("23")) {
errorBody.put("error", "NOT_NULL_CONSTRAINT_VIOLATION");
errorBody.put("message", "缺少必填字段");
} else {
errorBody.put("error", "DATA_INTEGRITY_ERROR");
errorBody.put("message", message);
}
} else {
errorBody.put("error", "UNKNOWN_DATA_ERROR");
errorBody.put("message", ex.getMessage());
}
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorBody);
}
}</string></map>
如何处理嵌套异常中的具体 SQL 错误信息
在实际开发中,DataIntegrityViolationException 往往包裹着多层异常。最内层通常是数据库驱动抛出的 SQLException。为了准确获取错误详情,需要逐级解包。例如,在 MySQL 中,唯一键冲突通常会抛出 MySQLIntegrityConstraintViolationException,其 getMessage() 方法直接包含 “Duplicate entry 'xxx' for key 'username'” 这样的清晰提示。通过提取这部分信息,前端可以直接展示给用户,告知具体是哪个字段发生了冲突,而无需后端进行复杂的映射转换。











