package com.sky.common.handler; import com.sky.common.constant.MessageConstant; import com.sky.common.exception.BaseException; import com.sky.common.result.Result; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import java.sql.SQLIntegrityConstraintViolationException; @RestControllerAdvice @Slf4j public class GlobalExceptionHandler { // 捕获业务异常 @ExceptionHandler public Result exceptionHandler(BaseException exception) { log.error("异常信息:{}", exception.getMessage()); return Result.error(exception.getMessage()); } // 处理SQL异常 public Result exceptionHandler(SQLIntegrityConstraintViolationException exception) { log.error("处理SQL异常:{}", exception.getMessage()); String message = exception.getMessage(); if (message.contains("Duplicate entry")) { // 截取用户名 String username = message.split(" ")[2]; // 错误信息 String errorMessage = username + MessageConstant.ALREADY_EXISTS; return Result.error(errorMessage); } else { return Result.error(MessageConstant.UNKNOWN_ERROR); } } }