From 2a9c95df5ae288d4162d3eceefe839da126556b0 Mon Sep 17 00:00:00 2001 From: LiShu <2945621619@qq.com> Date: Fri, 29 Nov 2024 16:44:55 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=85=A8=E5=B1=80=E5=BC=82?= =?UTF-8?q?=E5=B8=B8=E5=A4=84=E7=90=86=E5=99=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../sky/handler/GlobalExceptionHandler.java | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 sky-server/src/main/java/com/sky/handler/GlobalExceptionHandler.java diff --git a/sky-server/src/main/java/com/sky/handler/GlobalExceptionHandler.java b/sky-server/src/main/java/com/sky/handler/GlobalExceptionHandler.java new file mode 100644 index 0000000..7ffc45d --- /dev/null +++ b/sky-server/src/main/java/com/sky/handler/GlobalExceptionHandler.java @@ -0,0 +1,46 @@ +package com.sky.handler; + +import com.sky.constant.MessageConstant; +import com.sky.exception.BaseException; +import com.sky.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 { + + /** + * 捕获业务异常 + * @param ex + * @return + */ + @ExceptionHandler + public Result exceptionHandler(BaseException ex){ + log.error("异常信息:{}", ex.getMessage()); + return Result.error(ex.getMessage()); + } + + /* + * 处理sql异常 + * + * */ + @ExceptionHandler + public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){ + //Duplicate entry "zhangsan" for key '...' + String message = ex.getMessage(); + if(message.contains("Duplicate entry")){ + String[] split = message.split(" "); + String username = split[2]; + String msg = username + MessageConstant.ALREADY_EXISTS; + return Result.error(msg); + } + return Result.error(MessageConstant.UNKNOWN_ERROR); + } +}