Fixiaobai
2023-09-05 c9da1b0da1178911e383ddcaebecd1e088fa6004
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
package com.yuanchu.limslaboratory.handler;
 
import com.yuanchu.limslaboratory.exception.AuthException;
import com.yuanchu.limslaboratory.exception.MyFileException;
import com.yuanchu.limslaboratory.utils.MyUtil;
import com.yuanchu.limslaboratory.utils.ServletUtils;
import com.yuanchu.limslaboratory.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.apache.tomcat.util.http.fileupload.impl.SizeLimitExceededException;
import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MultipartException;
 
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.BindException;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.List;
import java.util.stream.Collectors;
 
 
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
 
    @Value("${spring.servlet.multipart.max-file-size}")
    private String maxFileSize;
 
    @Value("${spring.servlet.multipart.max-request-size}")
    private String maxRequestSize;
 
    @ExceptionHandler(SQLException.class)
    public Result<?> handlerSQLException(SQLException e)
    {
        log.error(e.getMessage().toLowerCase(), e);
        return Result.fail("数据操作失败!请联系管理员");
    }
 
    /**
     * 唯一值在数据库中重复
     * Duplicate entry ' ' for key ' '
     * @param e:重复键异常
     * @return 199
     */
    @ExceptionHandler
    public Result<?> DuplicateKeyException(DuplicateKeyException e) {
        log.error(String.valueOf(e));
        String message = e.getCause().getMessage();
        String[] split = message.split("'");
        String servletPath = ServletUtils.getRequest().getServletPath();
        System.out.println(servletPath);
        if("/user/add_new_personnel".equals(servletPath)){
            return Result.fail("账号重复,添加失败,请核对后操作。");
        }
        return Result.fail("重复添加:【" + split[1] + "】操作失败!");
    }
 
    @ExceptionHandler
    public Result<?> NullPointerException(NullPointerException e){
        e.printStackTrace();
        return Result.fail("部分参数为空,请检查!");
    }
 
    /** 运行时异常 */
    @ExceptionHandler(RuntimeException.class)
    public Result<?> runtimeExceptionHandler(RuntimeException e) {
        e.printStackTrace();
        return Result.fail("运行时异常");
    }
 
    /** 类型转换异常 */
    @ExceptionHandler(ClassCastException.class)
    public Result<?> classCastExceptionHandler(ClassCastException e) {
        e.printStackTrace();
        return Result.fail("类型转换异常");
    }
    /** 文件未找到异常 */
    @ExceptionHandler(FileNotFoundException.class)
    public Result<?> FileNotFoundException(FileNotFoundException e) {
        e.printStackTrace();
        return Result.fail("文件未找到异常");
    }
    /** 数字格式异常 */
    @ExceptionHandler(NumberFormatException.class)
    public Result<?> NumberFormatException(NumberFormatException e) {
        e.printStackTrace();
        return Result.fail("数字格式异常");
    }
    /** 安全异常 */
    @ExceptionHandler(SecurityException.class)
    public Result<?> SecurityException(SecurityException e) {
        e.printStackTrace();
        return Result.fail("安全异常");
    }
 
    /** 类型不存在异常 */
    @ExceptionHandler(TypeNotPresentException.class)
    public Result<?> TypeNotPresentException(TypeNotPresentException e) {
        e.printStackTrace();
        return Result.fail("类型不存在异常");
    }
 
    /** IO异常 */
    @ExceptionHandler(IOException.class)
    public Result<?> iOExceptionHandler(IOException e) {
        e.printStackTrace();
        return Result.fail("IO异常");
    }
 
    /** 未知方法异常 */
    @ExceptionHandler(NoSuchMethodException.class)
    public Result<?> noSuchMethodExceptionHandler(NoSuchMethodException e) {
        e.printStackTrace();
        return Result.fail("未知方法异常");
    }
 
    /** 数组越界异常 */
    @ExceptionHandler(IndexOutOfBoundsException.class)
    public Result<?> indexOutOfBoundsExceptionHandler(IndexOutOfBoundsException e) {
        e.printStackTrace();
        return Result.fail("数组越界异常");
    }
    /** sql语法错误异常 */
    @ExceptionHandler(BadSqlGrammarException.class)
    public Result<?> BadSqlGrammarException(BadSqlGrammarException e) {
        e.printStackTrace();
        return Result.fail("sql语法错误异常");
    }
 
    /** 无法注入bean异常 */
    @ExceptionHandler(NoSuchBeanDefinitionException.class)
    public Result<?> NoSuchBeanDefinitionException(NoSuchBeanDefinitionException e) {
        e.printStackTrace();
        return Result.fail("无法注入bean");
    }
 
    /** Http消息不可读异常 */
    @ExceptionHandler({HttpMessageNotReadableException.class})
    public Result<?> requestNotReadable(HttpMessageNotReadableException e) {
        e.printStackTrace();
        return Result.fail("Http消息不可读");
    }
 
    /** 400错误 */
    @ExceptionHandler({TypeMismatchException.class})
    public Result<?> requestTypeMismatch(TypeMismatchException e) {
        e.printStackTrace();
        return Result.fail("服务器异常");
    }
 
    /** 500错误 */
    @ExceptionHandler({ConversionNotSupportedException.class, HttpMessageNotWritableException.class})
    public Result<?> server500(RuntimeException e) {
        e.printStackTrace();
        return Result.fail("服务器异常");
    }
 
    /** 栈溢出 */
    @ExceptionHandler({StackOverflowError.class})
    public Result<?> requestStackOverflow(StackOverflowError e) {
        e.printStackTrace();
        return Result.fail("栈溢出异常");
    }
 
    /** 除数不能为0 */
    @ExceptionHandler({ArithmeticException.class})
    public Result<?> arithmeticException(ArithmeticException e) {
        e.printStackTrace();
        return Result.fail("除数不能为0异常");
    }
 
    /**
     *文件过大报错提示
     */
    @ExceptionHandler({MultipartException.class})
    public Result<?> fileUploadExceptionHandler(MultipartException  e) {
        String msg;
        Throwable rootCause = e.getRootCause();
        if (rootCause instanceof FileSizeLimitExceededException) {
            msg="上传文件过大【单个文件大小不得超过" + maxFileSize + "】";
        }else if(rootCause instanceof SizeLimitExceededException){
            msg="上传文件过大【总上传大小不得超过" + maxRequestSize + "】";
        }else {
            msg="文件上传失败【服务器异常】";
        }
        return Result.fail(msg);
    }
 
    /** 文件后缀名不通过返回提示 */
    @ExceptionHandler({MyFileException.class})
    public Result<?> myFileException(Exception e) {
        return Result.fail("抱歉不支持【" + e.getMessage() +"】后缀的文件!");
    }
 
    /**
     * 参数检验
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public Result<?> methodArgumentNotValidException(MethodArgumentNotValidException e) {
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        String message = allErrors.stream().map(s -> s.getDefaultMessage()).collect(Collectors.joining(";"));
        return Result.fail(message);
    }
 
    /** 其他错误 */
    @ExceptionHandler({Exception.class})
    public Result<?> exception(Exception e) {
        e.printStackTrace();
        return Result.fail("网络连接失败,请退出后再试");
    }
 
    @ExceptionHandler({AuthException.class})
    public Result<?> noAuth(AuthException e){
        return Result.fail(Integer.valueOf(e.getCode()),e.getMsg());
    }
 
 
}