Java格式化异常信息
Java格式化异常信息
程序运行报错会抛出一大串异常信息,不方便观察排错;
这里对异常信息进行格式化处理,获取主要的信息并进行显示,或短信通知、或邮件发送;
样例:
{"fileName":"Temp.java","message:":"/ by zero","nativeMethod":false,"timestamp:":1656401454368,"methodName":"getException","className":"com.example.sirirobot.temp.Temp","lineNumber":77}
JSON解析处理(https://www.sojson.com/):
{ "fileName": "Temp.java", "message:": "/ by zero", "nativeMethod": false, "time:": 1656400993861, "methodName": "getException", "className": "com.example.sirirobot.temp.Temp", "lineNumber": 76 }
java代码:
try { int i = 1/0; } catch (Exception e) { return handleExeption(e); }
public String handleExeption(Exception e) { //格式化输出异常信息 String s1 = JSONObject.toJSONString(e); JSONObject js = JSONObject.parseObject(s1); String s2 = JSONObject.parseObject(s1).getString("stackTrace"); Map map = JSONObject.parseArray(s2, Map.class).get(0); map.put("timestamp:",new Date().getTime()); map.put("type:",js.getString("@type")); map.put("message:",js.getString("message")); return JSON.toJSONString(map); }
备注:
短信通知:要钱的暂时给出参考网址:如何使用Java实现手机短信验证?详细过程介绍 java短信验证和注册

浙公网安备 33010602011771号