高效开采之:trycatch的线程堆栈信息转数组处理

原创
小哥 3年前 (2022-11-08) 阅读数 44 #大杂烩

在开发场景中,有时需要记录异常信息。java Exception异常堆栈信息在存储中处理。这也意味着,不会像以前那样。catch (Exception e)的例外e.printStackTrace();

catch (Exception e){
    e.printStackTrace();
}

需要传递异常。 printStackTrace 的构造函数转换为字符串,然后转换为库或相关处理。方法如下:

public static String getExceptionString(Exception e) throws IOException {
      //读取异常堆栈信息
      ByteArrayOutputStream arrayOutputStream=new ByteArrayOutputStream();
      e.printStackTrace(new PrintStream(arrayOutputStream));
      //通过字节数组转换输入和输出流。
      BufferedReader fr=new BufferedReader(new InputStreamReader(new ByteArrayInputStream(arrayOutputStream.toByteArray())));
      String str;
      StringBuilder exceptionStr=new StringBuilder();
      while ((str=fr.readLine())!=null){
          exceptionStr.append(str);
      }
      //一定要关闭小溪
      fr.close();
      return exceptionStr.toString();
  }

然后再catch它可以用于:

catch (Exception e) {
     String exceptionStr = getExceptionString(e);
     System.out.println(exceptionStr);//这里可以放入存储处理等。..
 }
版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除

热门