标签:author string get close 数据库配置 catch lse manager span
/** * 所有异常报错 * @param * @return * @throws Exception */ @ExceptionHandler(value = Exception.class) @ResponseBody public Result allExceptionHandler(HttpServletRequest request, Exception ex) { String path = request.getServletPath(); ErrorLogsUtil.error(ex,path); log.error("Exception:"+ ex.getMessage()); return ResultUtils.error("操作失败"); }
将异常 和 请求的路径作为参数传递
目前这里的数据库连接是写死的
package cn.com.connext.authority.utils; import cn.com.connext.authority.config.DruidProperties; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class ErrorLogsUtil { /** * @param: [e] * @return void * @Description 打印错误日志并保存到数据库 */ public static void error(Exception e,String path) { StackTraceElement stackTraceElement= e.getStackTrace()[0]; Connection con = null; try { Class.forName("com.mysql.jdbc.Driver"); con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/demo-boot?useSSL=false&characterEncoding=utf8", "root", "root"); } catch (SQLException e1) { e1.printStackTrace(); } catch (ClassNotFoundException e1) { e1.printStackTrace(); } PreparedStatement ps = null; String sql = "INSERT INTO error_logs VALUES (UUID(), NOW(), ?,?)"; try { ps = con.prepareStatement(sql); //打印日志,错在第几行 String errorInfo = e.toString()+",errorMassage:"+stackTraceElement+","+"errorLine:"+stackTraceElement.getLineNumber(); ps.setString(1, errorInfo); ps.setString(2,path); ps.execute(); } catch (SQLException e1) { e1.printStackTrace(); } finally { try { if(ps != null) { ps.close(); } if(con != null) { con.close(); } } catch (SQLException e1) { e1.printStackTrace(); } } } }
SQL
DROP TABLE IF EXISTS `error_logs`; CREATE TABLE `error_logs` ( `id` varchar(36) NOT NULL, `create_time` datetime DEFAULT NULL, `msg` varchar(500) DEFAULT NULL, `path` varchar(50) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
数据库配置用public static 会报错
标签:author string get close 数据库配置 catch lse manager span
原文地址:https://www.cnblogs.com/lyon91/p/10395334.html