2024-03-12 17:58:59 +08:00
|
|
|
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<String> exceptionHandler(BaseException exception) {
|
|
|
|
log.error("异常信息:{}", exception.getMessage());
|
|
|
|
return Result.error(exception.getMessage());
|
|
|
|
}
|
|
|
|
|
|
|
|
// 处理SQL异常
|
|
|
|
public Result<String> exceptionHandler(SQLIntegrityConstraintViolationException exception) {
|
2024-03-16 21:54:38 +08:00
|
|
|
log.error("处理SQL异常:{}", exception.getMessage());
|
|
|
|
|
2024-03-12 17:58:59 +08:00
|
|
|
String message = exception.getMessage();
|
|
|
|
if (message.contains("Duplicate entry")) {
|
2024-03-16 21:54:38 +08:00
|
|
|
// 截取用户名
|
|
|
|
String username = message.split(" ")[2];
|
|
|
|
// 错误信息
|
2024-03-12 17:58:59 +08:00
|
|
|
String errorMessage = username + MessageConstant.ALREADY_EXISTS;
|
|
|
|
return Result.error(errorMessage);
|
|
|
|
} else {
|
|
|
|
return Result.error(MessageConstant.UNKNOWN_ERROR);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|