Helius
2021-06-28 3cdddd8bb0a0b2cef27d44629647666579655877
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
package com.xzx.gc.common.exception;
 
import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.exceptions.ValidateException;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.xzx.gc.common.exception.wx.WxPayNotifyResponseException;
import com.xzx.gc.common.utils.BusinessUtil;
import com.xzx.gc.common.utils.MstRes;
import com.xzx.gc.common.utils.SpringUtil;
import com.xzx.gc.model.JsonResult;
import com.xzx.gc.model.MiException;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.ClientAbortException;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
 
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
 
/**
 * 异常处理器
 */
@RestControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
@Slf4j
public class MstExceptionHandler {
 
 
    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public MstRes handleException(Exception e) {
        String msg=e.getMessage();
        if(!com.xzx.gc.common.utils.StringUtils.isContainChinese(msg,true)){
            String methodAnnoByEx = getMethodAnnoByEx(e);
            if(StrUtil.isNotBlank(methodAnnoByEx)){
                msg=methodAnnoByEx;
            }
        }
        log.error(msg,e);
        MstRes error = MstRes.error(e.getMessage());
        error.put("debugMsg",ExceptionUtil.getMessage(e));
        return  error;
    }
 
    @ExceptionHandler({MaxUploadSizeExceededException.class})
    protected MstRes handleException(
            MaxUploadSizeExceededException e) {
        MstRes r = new MstRes();
        r.put("code",-1);
        r.put("msg", "单个大小不能超过4M");
        return  r;
    }
 
    @ExceptionHandler({ClientAbortException.class})
    protected MstRes handleException(
            ClientAbortException e) {
        MstRes r = new MstRes();
        r.put("msg", "服务器连接失败");
        return  r;
    }
 
    @ExceptionHandler(value = MiException.class)
    public JsonResult errorHandler(MiException e, HttpServletRequest request) throws Exception {
        if(request.getRequestURI().indexOf("/wxpay") != -1){
            return JsonResult.failMessage(e.getMessage());
        }
        JsonResult<T> t = new JsonResult<>();
        if(e.getMessage().equals("会话过期,重新登录")){
            t.setCode(-2);
        }else{
            t.setCode(-1);
        }
 
        t.setMsg(e.getMessage());
        return t;
    }
 
 
    /**
     * @Description: 捕捉 MethodArgumentNotValidException  用于@Requestbody
     * @Param: [ex]
     * @return: org.springframework.http.ResponseEntity<?>
     * @Author: zan.zhong
     * @Date: 2019/3/26
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    protected MstRes handleException(
            MethodArgumentNotValidException ex) {
        return outPutErrorInfo(ex.getBindingResult());
    }
 
    @ExceptionHandler({BindException.class})
    protected MstRes handleException(
            BindException ex) {
        return outPutErrorInfo(ex.getBindingResult());
    }
 
    @ExceptionHandler({PlatformException.class})
    protected MstRes handleException(
            PlatformException e) {
        MstRes r = new MstRes();
        r.put("code", -1);
        r.put("msg", e.getMessage());
        return  r;
    }
 
    @ExceptionHandler({RestException.class})
    protected MstRes handleException(
            RestException e) {
        if(SpringUtil.isDevOrTestOrCheck()) {
            log.debug(e.getMsg(), e);
        }
        MstRes r = new MstRes();
        r.put("code", e.getCode());
        r.put("msg", e.getMessage());
        return  r;
    }
 
    @ExceptionHandler({BusinessException.class})
    protected MstRes handleException(
            BusinessException e) {
        MstRes r = new MstRes();
        r.put("code", e.getCode());
        r.put("msg", e.getMessage());
        if(SpringUtil.isDev()) {
            r.put("debugMsg", e.getDebugMsg());
        }
        return  r;
    }
 
    @ExceptionHandler({ValidateException.class})
    protected MstRes handleException(
            ValidateException e) {
        log.warn(e.getMessage());
        MstRes r = new MstRes();
        r.put("code", -1);
        r.put("msg", e.getMessage());
        return  r;
    }
 
    @ExceptionHandler({WxPayNotifyResponseException.class})
    protected String handleException(
            WxPayNotifyResponseException e) {
        return  e.getMsg();
    }
 
 
    /**
     * @Description: 输出错误信息
     * @Param: [bindingResult]
     * @return: org.springframework.http.ResponseEntity<?>
     * @Author: zan.zhong
     * @Date: 2019/3/28
     */
    private MstRes outPutErrorInfo(BindingResult bindingResult) {
        String message = "";
        String viewMessage="";
        if (bindingResult.hasErrors()) {
            for (FieldError error : bindingResult.getFieldErrors()) {
                message += error.getField()+error.getDefaultMessage() + ",";
                viewMessage += error.getDefaultMessage() + ",";
            }
        }
        if(StringUtils.isNotBlank(message)){
            message=message.substring(0,message.length()-1);
        }
        if(StringUtils.isNotBlank(viewMessage)){
            viewMessage=viewMessage.substring(0,viewMessage.length()-1);
        }
        MstRes r = new MstRes();
        r.put("code", -1);
        r.put("msg", viewMessage);
        return r;
    }
 
    /**
     * 根据异常获取方法注释 若是中文异常则忽略
     * @param e
     * @return
     */
    private String getMethodAnnoByEx(Exception e){
        try {
            Throwable rootCause = ExceptionUtil.getRootCause(e);
            if(rootCause!=null){
                StackTraceElement[] stackTrace = rootCause.getStackTrace();
                if(stackTrace!=null&&stackTrace.length>0){
                    StackTraceElement stackTraceElement = stackTrace[0];
                    String methodName = stackTraceElement.getMethodName();
                    String className = stackTraceElement.getClassName();
                    Method methodByName = ReflectUtil.getMethodByName(Class.forName(className), methodName);
                    ApiOperation annotation = AnnotationUtil.getAnnotation(methodByName, ApiOperation.class);
                    if(annotation!=null){
                        return annotation.value()+"失败";
                    }
                }
            }
        }catch (Exception e1) {
            return null;
        }
        return null;
    }
}