Spring 共通异常捕获

说明

1
捕获异常,并发送邮件

代码

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
package com.tre.common.base;

import com.tre.common.utils.R;
import com.tre.mail.MailOutBox;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.WebRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;

@RestControllerAdvice
public class AutoResultExceptionHandler {

private static final Logger logger = LoggerFactory.getLogger(AutoResultExceptionHandler.class);

@Value("${emailUrl}")
private String emailUrl;

@Value("${emailUser}")
private String emailUser;

@Value("${emailPassward}")
private String emailPassward;

@Value("${emailFrom}")
private String emailFrom;

@Value("${emailTo}")
private String emailTo;

@Value("${toOther1}")
private String toOther1;

@Value("${toOther2}")
private String toOther2;

@Value("${emailTitle}")
private String emailTitle;

@ExceptionHandler(value = Exception.class)
public R handleOtherExceptions(final Exception ex, final WebRequest req) throws IOException {

ServletRequestAttributes attributes =
(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();

String branchcd = "";
if (request.getHeader("branchcd") != null) {
branchcd = request.getHeader("branchcd");
} else {
branchcd = (String) request.getSession().getAttribute("branchcd");
}

StringBuilder errorInfo = new StringBuilder();
StackTraceElement st = ex.getStackTrace()[0];
// for (StackTraceElement stackTraceElement : st) {
String exclass = st.getClassName();
String method = st.getMethodName();
int Number = st.getLineNumber();

ByteArrayOutputStream out = new ByteArrayOutputStream();
PrintStream pout = new PrintStream(out);
ex.printStackTrace(pout);
String ret = new String(out.toByteArray());
pout.close();
out.close();

errorInfo.append("错误类:" + exclass + "\n");
errorInfo.append("错误方法:" + method + "\n");
errorInfo.append("错误行数:" + Number + "\n");
errorInfo.append("错误原因:" + ret + "\n");
errorInfo.append("店铺:" + branchcd + "\n");

System.out.println(ret);
// }

MailOutBox.open(emailUrl, 25, emailUser, emailPassward)
.from(emailFrom)
.to(emailTo, toOther1, toOther2)
.subject(emailTitle)
.addText(errorInfo.toString())
.send()
.close();

return R.error(-1, ex.getMessage());
}
}