背景
目前依赖测试提的问题,没法做到实时监控,所以可以将环境的报错信息实时上传到钉钉群,可以at对应的人,对私有化部署的考虑到可能存在外网不能访问的问题,暂时不考虑,公司的sass环境是否考虑增加。
实现
1.增加统一错误处理切面
@ControllerAdvice
public class GlobalDefaultExceptionHandler {
private Logger logger = LoggerFactory.getLogger(GlobalDefaultExceptionHandler.class);
@ExceptionHandler(value = Exception.class)
public Object defaultErrorHandler(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception{
if(response.isCommitted()){
return null;
}
Integer code = ErrorCode.UN_KNOW.getCode();
String msg = null;
if (e instanceof AtlasException) {
logger.error("AtlasException,detail=", e);
code = ((AtlasException)e).getCode();
}else{
logger.error("uncatched exception,detail=", e);
}
msg = e.getMessage();
code = (code== null ? ErrorCode.UN_KNOW.getCode() : code);
ErrorLogger.core("应用报警", "errorCode={},msg={}",code, msg, e);
if (isJsonRequest(request)) {
ResponseResult responseResult = new ResponseResult();
responseResult.setCode(code);
responseResult.setMsg(msg);
responseJSON(response, responseResult);
return null;
}
logger.error("error uri : {}", request.getRequestURI(), e);
throw e;
}
private boolean isJsonRequest(HttpServletRequest request) {
String header = request.getHeader("content-type");
return header == null || header.contains("json");
}
private void responseJSON(HttpServletResponse response, Object obj) {
response.addHeader("Cache-Control", "no-cache");
response.setContentType("application/json;charset=UTF-8");
PrintWriter out = null;
try {
out = response.getWriter();
response.setStatus(HttpStatus.OK.value());
out.write(JSON.toJSONString(obj));
} catch (Exception e) {
} finally {
if (out != null) {
out.close();
}
}
}
}
2.其他代码
@Getter
public class AtlasException extends RuntimeException {
private Integer code;
private String msg;
private String enMsg;
public AtlasException() {
}
public AtlasException(String msg) {
super(msg);
this.enMsg = msg;
this.msg = msg;
}
public AtlasException(Integer code, String msg) {
super(msg);
this.code = code;
this.enMsg = msg;
this.msg = msg;
}
public AtlasException(Integer code, String msg, String enMsg) {
super(msg);
this.code = code;
this.msg = msg;
this.enMsg = enMsg;
}
public AtlasException(AtlasErrorCodeMsgI18n atlasErrorCodeMsgI18n) {
this(atlasErrorCodeMsgI18n.getCode(), atlasErrorCodeMsgI18n.getMsg(), atlasErrorCodeMsgI18n.getEnMsg());
}
public AtlasException(AtlasErrorCodeMsgI18n atlasErrorCodeMsgI18n, Object... objs) {
this(atlasErrorCodeMsgI18n.getCode(), MessageFormat.format(atlasErrorCodeMsgI18n.getMsg(), objs),
MessageFormat.format(atlasErrorCodeMsgI18n.getEnMsg(), objs));
}
public AtlasException(ErrorCode errorCode) {
super(errorCode.getMsg());
this.code = errorCode.getCode();
this.enMsg = errorCode.getMsg();
}
public AtlasException(ErrorCode errorCode, Object... obj) {
super(MessageFormat.format(errorCode.getMsg(), obj));
this.code = errorCode.getCode();
this.enMsg = MessageFormat.format(errorCode.getMsg(), obj);
}
}
网友评论