xuekang
2024-05-13 15a0280ae9e7db96fdf0744c722d214d2cb5a0e5
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
48
49
50
51
52
53
54
55
package com.nuvole.four.exception;
 
import cn.hutool.core.util.StrUtil;
import com.nuvole.common.domain.emnu.CommonResultEmnu;
import com.nuvole.common.domain.result.CommonResult;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
 
import java.io.PrintWriter;
import java.io.StringWriter;
 
/**
 * 类描述: 全局异常类
 *
 * @author dqh
 * @date  2024-04-09 19:25
 * @version 1.0
 **/
@ControllerAdvice
@Slf4j
public class Exceptionhandler {
 
    @ExceptionHandler(value = IllegalArgumentException.class)
    @ResponseBody
    private CommonResult IllegalArgumentException(HttpServletRequest req, IllegalArgumentException e) {
        log.error(getExceptionStackMsg(e));
        if(StrUtil.isNotBlank(e.getMessage())){
            return new CommonResult(CommonResultEmnu.INVALID_PARAMS, e.getMessage());
        }else {
            return new CommonResult(CommonResultEmnu.INVALID_PARAMS, "不合法的参数");
        }
    }
 
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    private CommonResult Exception(HttpServletRequest req, HttpServletResponse resp, Exception e) {
        //if (!(req.getHeader("accept").contains("application/json")//非异步请求
        //|| (req.getHeader("X-Requested-With") != null && req.getHeader("X-Requested-With").contains("XMLHttpRequest")))) {
        //}
        log.error(getExceptionStackMsg(e));
        return new CommonResult(CommonResultEmnu.SERVER_ERR, "服务异常");
    }
 
    public static String getExceptionStackMsg(Exception e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw, true));
        String strs = sw.toString();
        return strs;
    }
 
}