使用 @controlleradvice 结合自定义异常类,通过 @exceptionhandler 注解拦截数据迁移冲突异常。在配置中注册全局异常处理器,针对特定的业务异常类型(如 datamigrationconflictexception)编写处理逻辑,返回统一的错误响应结构。

如何定义并抛出数据迁移冲突异常
需要创建一个继承自 RuntimeException 的自定义异常类,并在数据迁移服务层检测到冲突时主动抛出。这确保了异常能够被上层的全局处理器捕获,而不是直接导致应用崩溃。

package com.example.exception;
public class DataMigrationConflictException extends RuntimeException {
private final String conflictId;
private final String message;
public DataMigrationConflictException(String conflictId, String message) {
super(message);
this.conflictId = conflictId;
this.message = message;
}
public String getConflictId() {
return conflictId;
}
public String getMessage() {
return message;
}
}
在迁移服务中,当发现主键冲突或数据不一致时,实例化上述异常并抛出:
if (existingRecord != null) {
throw new DataMigrationConflictException("REC-001", "Duplicate record found during migration");
}
如何在全局处理器中捕获并格式化响应
创建配置类实现 ResponseBodyAdvice 或使用 @RestControllerAdvice,在其中定义 @ExceptionHandler 方法。该方法接收自定义异常对象,构建包含状态码、错误信息和冲突ID的JSON响应体,确保前端能解析具体的冲突细节。

package com.example.config;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(DataMigrationConflictException.class)
public ResponseEntity<ErrorResponse> handleConflictException(DataMigrationConflictException ex) {
ErrorResponse errorResponse = new ErrorResponse(
HttpStatus.CONFLICT.value(),
ex.getMessage(),
ex.getConflictId()
);
return new ResponseEntity<>(errorResponse, HttpStatus.CONFLICT);
}
}
class ErrorResponse {
private int status;
private String message;
private String conflictId;
public ErrorResponse(int status, String message, String conflictId) {
this.status = status;
this.status = status;
this.message = message;
this.conflictId = conflictId;
}
// Getters and Setters omitted for brevity
}
如何处理未捕获的通用运行时异常
除了特定冲突异常外,还需定义一个兜底的异常处理方法,用于捕获所有未被显式处理的 RuntimeException。这保证了即使出现意外的数据迁移错误,系统也能返回规范的500错误响应,避免暴露堆栈信息给客户端。
@ExceptionHandler(RuntimeException.class)
public ResponseEntity<ErrorResponse> handleRuntimeException(RuntimeException ex) {
ErrorResponse errorResponse = new ErrorResponse(
HttpStatus.INTERNAL_SERVER_ERROR.value(),
"Internal server error occurred",
null
);
return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}


















