美文网首页
SpringBoot实战—全局异常处理器

SpringBoot实战—全局异常处理器

作者: 遇见编程 | 来源:发表于2024-07-08 09:23 被阅读0次
    /**
     * 全局异常处理器,处理项目中抛出的业务异常
     */
    @RestControllerAdvice
    @Slf4j
    public class GlobalExceptionHandler {
    
        /**
         * 捕获业务异常
         * @param ex
         * @return
         */
        @ExceptionHandler
        public Result exceptionHandler(BaseException ex){
            log.error("异常信息:{}", ex.getMessage());
            return Result.error(ex.getMessage());
        }
    
        /**
         * 处理SQL异常
         * @param ex
         * @return
         */
        @ExceptionHandler
        public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
            //Duplicate entry 'zhangsan' for key 'employee.idx_username'
            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);
            }else{
                return Result.error(MessageConstant.UNKNOWN_ERROR);
            }
        }
    }
    
    /**
     * 后端统一返回结果
     * @param <T>
     */
    @Data
    public class Result<T> implements Serializable {
    
        private Integer code; //编码:1成功,0和其它数字为失败
        private String msg; //错误信息
        private T data; //数据
    
        public static <T> Result<T> success() {
            Result<T> result = new Result<T>();
            result.code = 1;
            return result;
        }
    
        public static <T> Result<T> success(T object) {
            Result<T> result = new Result<T>();
            result.data = object;
            result.code = 1;
            return result;
        }
    
        public static <T> Result<T> error(String msg) {
            Result result = new Result();
            result.msg = msg;
            result.code = 0;
            return result;
        }
    
    }
    

    相关文章

      网友评论

          本文标题:SpringBoot实战—全局异常处理器

          本文链接:https://www.haomeiwen.com/subject/nipwcjtx.html