web模块添加全局异常拦截处理,针对com.product 包下所有的controller 未处理的异常进行通用处理
已添加1个文件
49 ■■■■■ 文件已修改
src/main/java/com/product/ChatServiceExceptionAdvice.java 49 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
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);
    }
}