package com.itheima.exception;
import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.sql.SQLIntegrityConstraintViolationException;
/**
* 全局异常处理器
*/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* 处理数据库完整性约束异常(如手机号、用户名重复)
*/
@ExceptionHandler
public Result handleSQLIntegrityConstraintViolationException(SQLIntegrityConstraintViolationException e) {
log.error("数据库完整性约束异常: {}", e.getMessage());
String message = e.getMessage();
if (message != null && message.contains("Duplicate entry")) {
// 提取冲突的值, 报错格式: Duplicate entry '13800000001' for key 'phone'
String value = message.split(" ")[2].replace("'", "");
if (value.isEmpty()) {
return Result.error("手机号/用户名等唯一字段为空或重复, 请检查提交的数据");
}
return Result.error(value + " 已存在");
}
return Result.error("数据库操作失败");
}
/**
* 兜底处理所有其他异常
*/
@ExceptionHandler(Exception.class)
public Result handleException(Exception e) {
log.error("程序运行出现异常: ", e);
return Result.error("系统繁忙, 请稍后重试");
}
}