/** * 所有异常报错 * @param * @return * @throws Exception */ @ExceptionHandler(value = Exception.class) @ResponseBody public Result allExceptionHandler(HttpServletRequest request, Exception ex) {
RequestWrapper requestWrapper = new RequestWrapper(request);
String body = requestWrapper.getBody();
log.info("【参数】" + body);
String path = request.getServletPath();
ErrorLogsUtil.error(ex,path,body);
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.setString(3,params);
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` text,
`path` varchar(100) DEFAULT NULL,
`params` varchar(500) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
数据库配置用public static 会报错