sky-take-out/sky-common/src/main/java/com/sky/common/handler/GlobalExceptionHandler.java

38 lines
1.3 KiB
Java

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) {
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);
}
}
}