1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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);
    }
 
 
}