xiangpei
2024-06-17 99701274f83bc7c54beedfe7e18577e9d6b7198e
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package com.ycl.jxkg.config.spring.exception;
 
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ycl.jxkg.base.Result;
import com.ycl.jxkg.base.SystemCode;
import com.ycl.jxkg.utils.ErrorUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
 
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;
 
/**
 * @version 3.5.0
 * @description: The type Exception handle.
 * Copyright (C), 2020-2024, 武汉思维跳跃科技有限公司
 * @date 2021/12/25 9:45
 */
@RestControllerAdvice
public class ExceptionHandle {
 
    private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);
    /**
     * 公司项目的包结构,用于缩短错误日志的长度
     */
    private final static String COMPANY_PACKAGE = "com.ycl.jxkg.";
 
    /**
     * Handler rest response.
     *
     * @param e the e
     * @return the rest response
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result handler(Exception e, HttpServletRequest request) {
        String errMsg = String.format("系统异常-%s", e.getMessage());
        this.printExceptionLocation(e, request, errMsg);
        return new Result<>(SystemCode.InnerError.getCode(), SystemCode.InnerError.getMessage());
    }
 
    /**
     * Handler rest response.
     *
     * @param e the e
     * @return the rest response
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public Result handler(RuntimeException e, HttpServletRequest request) {
        String errMsg = String.format("系统异常-%s", e.getMessage());
        this.printExceptionLocation(e, request, errMsg);
        return new Result<>(SystemCode.InnerError.getCode(), e.getMessage());
    }
 
    /**
     * JSON传参数据校验异常
     *
     * @param e
     * @param request
     * @return
     * @throws JsonProcessingException
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e,
                                                        HttpServletRequest request) throws JsonProcessingException {
        List<String> err = e.getBindingResult().getAllErrors().stream().map(error -> error.getDefaultMessage()).collect(Collectors.toList());
        String s = new ObjectMapper().writeValueAsString(err);
        String errMsg = String.format("参数校验失败-%s", s);
        this.printExceptionLocation(e, request, errMsg);
        return Result.fail(HttpStatus.INTERNAL_SERVER_ERROR.value(), s);
    }
 
    /**
     * Handler rest response.
     *
     * @param e the e
     * @return the rest response
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public Result handler(BindException e) {
        String errorMsg = e.getBindingResult().getAllErrors().stream().map(file -> {
            FieldError fieldError = (FieldError) file;
            return ErrorUtil.parameterErrorFormat(fieldError.getField(), fieldError.getDefaultMessage());
        }).collect(Collectors.joining());
        return new Result<>(SystemCode.ParameterValidError.getCode(), errorMsg);
    }
 
    /**
     * 请求方式不支持异常
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
                                                      HttpServletRequest request) {
        String errMSg = String.format("不支持%s请求", e.getMethod());
        this.printExceptionLocation(e, request, errMSg);
        return Result.fail(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
    }
 
    /**
     * 打印异常出现位置
     *
     * @param e
     */
    private void printExceptionLocation(Throwable e, HttpServletRequest request, String errMsg) {
        StackTraceElement stackTraceElement = e.getStackTrace()[0];
        String className = stackTraceElement.getClassName().contains(COMPANY_PACKAGE) ?
                stackTraceElement.getClassName().split(COMPANY_PACKAGE)[1] : stackTraceElement.getClassName();
        logger.error("接口:【{}】, 异常类:【{}】,方法:【{}】,所在行:【{}】, 错误信息:【{}】",
                request.getRequestURI(),
                className,
                stackTraceElement.getMethodName(),
                stackTraceElement.getLineNumber(),
                errMsg);
    }
}