guang
2023-05-06 397c6003970432a8009b81916e55754c1874e03d
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
package com.hx.other.service.config;
 
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.hx.exception.ParamException;
import com.hx.exception.ServiceException;
import com.hx.exception.TipsException;
import com.hx.resultTool.ResponseCode;
import com.hx.resultTool.Result;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
 
import javax.servlet.ServletException;
import java.io.FileNotFoundException;
import java.io.IOException;
 
/**
 * 统一异常处理中心
 *
 * @Author: cmg
 * @Date: 2023/4/23 10:29
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
 
    /**
     * 参数校验错误异常
     *
     * @param e MethodArgumentNotValidException|BindException
     * @return ResponseData
     */
    @ExceptionHandler(value = {BindException.class, MethodArgumentNotValidException.class})
    public Result bindExceptionHandler(Exception e) {
        BindingResult bindingResult;
        if (e instanceof BindException) {
            bindingResult = ((BindException) e).getBindingResult();
        } else {
            bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
        }
        StringBuilder stringBuilder = new StringBuilder();
        bindingResult.getAllErrors().forEach(
                objectError ->
                        stringBuilder.append(",").append(objectError.getDefaultMessage())
        );
        String errorMessage = stringBuilder.toString();
        errorMessage = errorMessage.substring(1, errorMessage.length());
        log.error(getExceptionInformation(e));
        return Result.failure(ResponseCode.ERROR_PARAMS_VALIDATOR,errorMessage);
    }
 
    /**
     * 捕获统一提示异常
     *
     * @param e AbstractGlobalException
     * @return ResponseData
     */
    @ExceptionHandler(value = TipsException.class)
    public Result customExceptionHandler(TipsException e) {
        //和爷要求删除
//        e.printStackTrace();
//        logger.error(getExceptionInformation(e));
        return Result.failure(ResponseCode.ERROR_TIPS,e.getMessage());
    }
 
    /**
     * 捕获统一业务/判断异常
     *
     * @param e AbstractGlobalException
     * @return ResponseData
     */
    @ExceptionHandler(value = ServiceException.class)
    public Result customExceptionHandler(ServiceException e) {
        e.printStackTrace();
        log.error(getExceptionInformation(e));
        return Result.failure(ResponseCode.ERROR_SERVICE_VALIDATOR,e.getMessage());
    }
 
    /**
     * 捕获统一业务/判断异常
     *
     * @param e AbstractGlobalException
     * @return ResponseData
     */
    @ExceptionHandler(value = ParamException.class)
    public Result customExceptionHandler(ParamException e) {
        //e.printStackTrace();
        //logger.error(getExceptionInformation(e));
        return Result.failure(ResponseCode.ERROR_PARAMS_VALIDATOR,e.getMessage());
    }
 
    /**
     * 捕获body空报错异常和入参类型异常
     *
     * @param e AbstractGlobalException
     * @return ResponseData
     */
    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    public Result customHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        if(e.getCause() instanceof InvalidFormatException){
            //入参类型错误
            return Result.failure(ResponseCode.ERROR_PARAMS_VALIDATOR,"参数类型错误:"+((InvalidFormatException) e.getCause()).getOriginalMessage());
        }
        return Result.failure(ResponseCode.ERROR_TIPS,"传参结构不能为空!");
    }
 
    /**
     * 捕获未知异常
     *
     * @param e Exception
     * @return ResponseData
     */
    @ExceptionHandler(value = Exception.class)
    public Result commonExceptionHandler(Exception e) throws ServletException {
        String errMsg = "系统错误!";
        if (e instanceof ServletException) {
            throw (ServletException) e;
        }else if(e instanceof ArrayIndexOutOfBoundsException){
            errMsg = "系统错误(sizeErr)!";
        }else if(e instanceof FileNotFoundException){
            errMsg = "系统错误(fileNot)!";
        }else if(e instanceof IOException){
            errMsg = "系统错误(IO)!";
        }else if(e instanceof NullPointerException){
            errMsg = "系统错误(null)!";
        }else if(e instanceof BadSqlGrammarException){
            errMsg = "系统错误(sql)!";
        }else if(e instanceof MethodArgumentTypeMismatchException){
            errMsg = "系统错误(参数类型错误)!";
        } else if (e instanceof HttpMessageNotReadableException){
            errMsg = "参数格式错误01!";
        }else if (e.getCause() instanceof InvalidFormatException){
            errMsg = "参数格式错误02!";
        }
        log.error(getExceptionInformation(e));
        return Result.failure(ResponseCode.ERROR_SYSTEM, errMsg);
    }
 
    /**
     * 获取异常信息
     * @param ex
     * @return
     */
    public static String getExceptionInformation(Exception ex){
        String sOut = ex.getMessage() + "\r\n";
        StackTraceElement[] trace = ex.getStackTrace();
        for (StackTraceElement s : trace) {
            sOut += "\tat " + s + "\r\n";
        }
        return sOut;
    };
}