Springboot统一异常处理并保存到数据库
一.统一异常处理
在springboot项目中利用@ControllerAdvice 这个注解可以更好的实现异常的捕获处理。
@ControllerAdvice,是spring3.2提供的新注解,从名字上就可以看出大体的意思是控制器增强。
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface ControllerAdvice {
}
二.创建ExceptionController类
创建 ExceptionController,并添加 @ControllerAdvice注解。
import com.left.druid.utils.Exception.ErrorLogsUtil;
import com.left.enums.CodeEnums;
import com.left.pub.LpayException;
import com.left.pub.ResponseData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
/**
* Created by pillar on 2017/3/27.
* qq 347637454
*/
@ControllerAdvice
public class ExceptionHandlers {
Logger logger = LoggerFactory.getLogger(ExceptionHandlers.class);
@ExceptionHandler(value = Exception.class)
@ResponseBody
public ResponseData handle(Exception e) {
ErrorLogsUtil.error(e); //将异常写入数据库
if (e instanceof LpayException) {
LpayException pillarException = (LpayException) e;
return new ResponseData(pillarException.getStatus());
}else if (e instanceof MethodArgumentTypeMismatchException){
return new ResponseData(CodeEnums.PARAM_TYPE_ERROR,(Object)((MethodArgumentTypeMismatchException) e).getName());
}else {
logger.info(e.toString());
e.printStackTrace();
return new ResponseData(CodeEnums.ERROR);
}
}
}
其中ResponseData类为封装的统一返回对象。
import com.fasterxml.jackson.annotation.JsonInclude;import com.left.enums.CodeEnums;
import java.io.Serializable;
/**
*
* @date 2017/3/27
* qq 347637454
* 统一返回对象
*/
public class ResponseData implements Serializable{
/**
* 返回数据
*/
private Object data;
/**
* 错误描述
*/
private String msg;
private int code;
@JsonInclude(JsonInclude.Include.NON_NULL)
private String sign;
public String getSign() {
return sign;
}
public void setSign(String sign) {
this.sign = sign;
}
public ResponseData(CodeEnums status) {
this.msg = status.getMessage();
this.code = status.getCode();
}
public ResponseData() {
}
public ResponseData(Object data,String api_key){
this.data = data;
this.msg = CodeEnums.SUCCESS.getMessage();
this.code = CodeEnums.SUCCESS.getCode();
this.sign = api_key;
}
public ResponseData(CodeEnums enums,Object data) {
this.data = data;
this.msg = enums.getMessage();
this.code = enums.getCode();
}
public ResponseData(int code,String msg){
this.code =code;
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
@Override
public String toString() {
return "ResponseData{" +
"data=" + data +
", msg="" + msg + """ +
", code=" + code +
", sign="" + sign + """ +
"}";
}
}
其中还有句代码为将异常写入数据库,需要ErrorLogsUtil.java工具类
import java.sql.Connection;import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* @Date 14:29 2018/05/29
* @Description 错误日志工具
*/
public class ErrorLogsUtil {
/**
* @param: [e]
* @return void
* @Description 打印错误日志并保存到数据库
*/
public static void error(Exception e) {
StackTraceElement stackTraceElement= e.getStackTrace()[0];
Connection con = null;
try {
Class.forName(MySqlConfig.driver);
con = (Connection) DriverManager.getConnection(MySqlConfig.url, MySqlConfig.username, MySqlConfig.password);
} catch (SQLException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
PreparedStatement ps = null;
String sql = "INSERT INTO itc_error_logs VALUES (UUID(), NOW(), ?, ?)";
try {
ps = con.prepareStatement(sql);
//打印日志,错在第几行
String errorInfo = e.toString()+",errorMassage:"+stackTraceElement+","+"errorLine:"+stackTraceElement.getLineNumber();
ps.setString(1, errorInfo);
ps.execute();
} catch (SQLException e1) {
e1.printStackTrace();
} finally {
try {
if(ps != null) {
ps.close();
}
if(con != null) {
con.close();
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
}
以上是 Springboot统一异常处理并保存到数据库 的全部内容, 来源链接: utcz.com/z/518206.html