使用 @restcontrolleradvice 配合自定义异常类,通过 @exceptionhandler 注解拦截数据迁移过程中抛出的特定异常。在控制器增强器中定义处理逻辑,将异常信息封装为统一的 json 响应返回给前端或调用方。

如何定义并捕获数据迁移中的业务异常
直接回答:创建一个继承自 RuntimeException 的自定义异常类 DataMigrationException,并在迁移服务中抛出该异常。全局异常处理器会捕获此异常并返回错误码与消息。

package com.example.exception;
public class DataMigrationException extends RuntimeException {
private final String errorCode;
public DataMigrationException(String message, String errorCode) {
super(message);
this.errorCode = errorCode;
}
public String getErrorCode() {
return errorCode;
}
}
package com.example.service;
import com.example.exception.DataMigrationException;
import org.springframework.stereotype.Service;
@Service
public class MigrationService {
public void migrateData(String source, String target) {
if (source == null || target == null) {
throw new DataMigrationException("Source or target is null", "MIG001");
}
// 模拟迁移逻辑
System.out.println("Migrating from " + source + " to " + target);
}
}
预期结果:当传入空参数时,系统抛出 DataMigrationException,错误码为 MIG001,消息为 Source or target is null。
如何在全局处理器中统一返回异常响应
直接回答:使用 @RestControllerAdvice 定义一个全局异常处理类,在其中添加 @ExceptionHandler(DataMigrationException.class) 方法,该方法接收异常对象并返回 ResponseEntity 类型的统一错误响应体。

package com.example.config;
import com.example.exception.DataMigrationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(DataMigrationException.class)
public ResponseEntity<errorresponse> handleDataMigrationException(DataMigrationException ex) {
ErrorResponse error = new ErrorResponse(ex.getErrorCode(), ex.getMessage());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(error);
}
}
class ErrorResponse {
private String code;
private String message;
public ErrorResponse(String code, String message) {
this.code = code;
this.message = message;
}
public String getCode() { return code; }
public String getMessage() { return message; }
}</errorresponse>
预期结果:API 调用失败时,返回 HTTP 400 状态码,JSON 格式包含 code 和 message 字段。
当迁移过程中出现数据库连接超时异常时如何处理
直接回答:在同一个全局异常处理器中添加对 SQLException 或 Spring 的 DataAccessException 的处理逻辑,将其转换为 DataMigrationException 或直接返回通用的迁移失败响应,确保数据库底层异常不会泄露给客户端。











