From ef644681feace871f3b9b7a255c7eba0e2a42a3c Mon Sep 17 00:00:00 2001 From: 许鹏程 <1821349743@qq.com> Date: 星期三, 18 九月 2024 10:18:49 +0800 Subject: [PATCH] web模块添加全局异常拦截处理,针对com.product 包下所有的controller 未处理的异常进行通用处理 --- src/main/java/com/product/ChatServiceExceptionAdvice.java | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 files changed, 49 insertions(+), 0 deletions(-) diff --git a/src/main/java/com/product/ChatServiceExceptionAdvice.java b/src/main/java/com/product/ChatServiceExceptionAdvice.java new file mode 100644 index 0000000..abe6888 --- /dev/null +++ b/src/main/java/com/product/ChatServiceExceptionAdvice.java @@ -0,0 +1,49 @@ +package com.product; + +import cn.hutool.json.JSONUtil; +import com.product.common.lang.StringUtils; +import com.product.core.exception.BaseException; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +import java.util.HashMap; +import java.util.Map; + +/** + * @author cheng + * @date 2024骞�9鏈�18鏃�10:17:42 + * @description 鍏ㄥ眬寮傚父澶勭悊 + */ +@RestControllerAdvice +@Slf4j +public class ChatServiceExceptionAdvice { + @ResponseBody + @ExceptionHandler(Exception.class) + public String exceptionHandler(Exception e) { + Map<String, Object> resultMap = new HashMap<>(); + resultMap.put("status", "error"); + if (e instanceof BaseException) { + BaseException exception = (BaseException) e; + resultMap.put("code", exception.getCode()); + resultMap.put("msg", exception.getMessage()); + log.error("鍏ㄥ眬寮傚父鎷︽埅", exception); + } else { + String message = e.getMessage(); + if (StringUtils.inString(message)) { + message = "鎺ュ彛璇锋眰閿欒锛屾湭鐭ュ紓甯�"; + } else { + message = "鎺ュ彛璇锋眰閿欒锛�" + message; + } + resultMap.put("code", "00000"); + resultMap.put("msg", message); + log.error("鍏ㄥ眬寮傚父鎷︽埅锛氭湭鐭ュ紓甯�", e); + } + return JSONUtil.toJsonStr(resultMap); + } + + +} + + -- Gitblit v1.9.2