错误通知异常捕获类,钉钉通知发送类
package com.jzlife.nurse.exception;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import com.jzlife.nurse.dingding.SendHttps;
import com.jzlife.nurse.util.ResponseUtil;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
@ControllerAdvice
public class ExceptionAdvice {
@Autowired
RedisTemplate redisTemplate;
@Autowired
SendHttps sendHttps;
private static final Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);
/**
* 应用到所有@RequestMapping注解方法,在其执行之前初始化数据绑定器
*
* @param binder
*/
@InitBinder
public void initBinder(WebDataBinder binder) {
}
/**
* 把值绑定到Model中,使全局@RequestMapping可以获取到该值
*
* @param model
*/
// @ModelAttribute
// public void addAttributes(Model model) {
// model.addAttribute("author", "Magical Sam");
// }
/**
* 全局异常捕捉处理
*
* @param ex
* @return
*/
// @RequestMapping
@ResponseBody
@ExceptionHandler({ Error.class, Exception.class, Throwable.class })
public Object errorHandler(HttpServletRequest request, Exception ex) {
ex.printStackTrace();
// logger.info("sys_exception:" + ex.getMessage() + "/n" + ex.toString());
String url = request.getRequestURI();
if (!(url.indexOf("find") != -1 || url.indexOf("select") != -1)) {// 重复提交校验 urlRequestConfig.comperUrl(url)
String token = request.getHeader("token");
if (null == token) {
token = request.getParameter("token");
}
if (token != null) {
try {
redisTemplate.delete(token + url);
} catch (Exception e) {
}
}
}
if (ex instanceof LoginException) {
// return new ResponseEntity<Map<String, Object>>(obj, HttpStatus.UNAUTHORIZED);
return ResponseUtil.fail401();// 登录过时或未登录
}
if (ex instanceof PromiseException) {
return ResponseUtil.fail400();// 没权限
}
if (ex instanceof MethodArgumentNotValidException) {// 业务校验不通过
MethodArgumentNotValidException exmessage = (MethodArgumentNotValidException) ex;
return ResponseUtil.fail502(exmessage.getBindingResult().getFieldError().getDefaultMessage());
}
//除了登录和自定义业务校验,其他都通知
sendHttps.sendStr(ex.toString() + "---" +getErrorMsg(ex));
if (ex instanceof BusinessException) {// 业务异常
return ResponseUtil.fail(ex.getMessage());
}
if (ex instanceof UnsupportException) {// 业务异常
return ResponseUtil.fail501(ex.getMessage());
}
Map<String, Object> obj = new HashMap<String, Object>();
obj.put("errno", 502);// 其他错误
obj.put("data", ex.toString() + "---" +getErrorMsg(ex));
obj.put("requesturl", request.getRequestURI());
return obj;
}
public String getErrorMsg(Exception ex) {
StringBuilder sbException = new StringBuilder();
int i = 0;
for (StackTraceElement ele : ex.getStackTrace()) {
sbException
.append(ele.getClassName() + ele.getMethodName() + ele.getFileName() + ele.getLineNumber() + "\n");
if (i > 4) {
break;
}
i++;
}
return sbException.toString();
}
}
package com.jzlife.nurse.dingding;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
@Component
public class SendHttps {
private static Logger logger = LoggerFactory.getLogger(SendHttps.class);
/**
* 发送POST请求,参数是Map, contentType=x-www-form-urlencoded
*
* @param url
* @param mapParam
* @return
*/
public static String sendPostByMap(String url, Map<String, Object> mapParam) {
Map<String, String> headParam = new HashMap<String, String>();
headParam.put("Content-type", "application/json;charset=UTF-8");
return sendPost(url, mapParam, headParam);
}
@Async
public void sendStr(String msg) {
// 钉钉的webhook
String dingDingToken = "https://oapi.dingtalk.com/robot/send?access_token=b137c72e5ed1a69e54ea3ce0a153680ae3fd8a3ba9cdf8d3ad6f8d54f4c35b0f";
// 关键词
String keyword = "系统bug报错通知:";
// 请求的JSON数据,这里我用map在工具类里转成json格式
Map<String,Object> text=new HashMap<String, Object>();
text.put("content",keyword+msg);
Map<String,Object> json=new HashMap<String, Object>();
json.put("msgtype","text");
json.put("text",text);
// 发送post请求
String response = SendHttps.sendPostByMap(dingDingToken, json);
System.out.println("通知相应结果:"+response);
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url 发送请求的 URL
* @param param 请求参数,
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, Map<String, Object> param, Map<String, String> headParam) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性 请求头
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Fiddler");
if (headParam != null) {
for (Entry<String, String> entry : headParam.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
}
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(JSON.toJSONString(param));
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
logger.info("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
}
package com.jzlife.nurse.exception;
public class BusinessException extends RuntimeException {
private static final long serialVersionUID = 1L;
private Exception e;
public BusinessException(String msg,Throwable cause) {
this.e = new Exception(msg,cause);
}
public Exception getE() {
return e;
}
public void setE(Exception e) {
this.e = e;
}
public BusinessException() {
}
public BusinessException(String msg) {
super(msg);
}
}