码迷,mamicode.com
首页 > 其他好文 > 详细

重构获取异常栈信息--printStackTrace

时间:2014-08-08 21:23:36      阅读:326      评论:0      收藏:0      [点我收藏+]

标签:重构   异常栈信息   

MyStackTrace:

/** 
 * 
 * @author wumingkun
 * @version 1.0.0
 * @Description
 */

package com.demo.stacktrace;

import java.io.PrintStream;

/**
 * @author wumingkun
 * 
 */
public class MyStackTrace {
	public static String getStackTrace(Throwable errors) {
		StringBuffer result = new StringBuffer();
		result.append(errors);
		StackTraceElement[] trace = errors.getStackTrace();
		for (int i = 0; i < trace.length; i++)
			result.append("\n\tat " + trace[i]);
		 Throwable ourCause = errors.getCause();
         if (ourCause != null)
             result.append(getStackTraceAsCause(ourCause, trace));
		return result.toString();
	}

	private static String  getStackTraceAsCause(
			Throwable ourCause,StackTraceElement[] causedTrace) {
		StringBuffer result=new StringBuffer();
		StackTraceElement[] trace = ourCause.getStackTrace();
		int m = trace.length - 1, n = causedTrace.length - 1;
		while (m >= 0 && n >= 0 && trace[m].equals(causedTrace[n])) {
			m--;
			n--;
		}
		int framesInCommon = trace.length - 1 - m;
		result.append("\nCaused by: " + ourCause);
		for (int i = 0; i <= m; i++)
			result.append("\n\tat " + trace[i]);
		if (framesInCommon != 0)
			result.append("\n\t... " + framesInCommon + " more");

		Throwable tempCause = ourCause.getCause();
		if (tempCause != null)
			result.append(getStackTraceAsCause(tempCause, trace));
		return result.toString();
	}

}


StackTraceTest:

/**
 * 
 * @author wumingkun
 * @version 1.0.0
 * @Description
 */

package com.demo.stacktrace;

/**
 * @author wumingkun
 *
 */
public class StackTraceTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			m1();
		} catch (Exception e) {
			System.out.println(MyStackTrace.getStackTrace(e));//直接返回异常栈信息字符串
		}
	}

	/**
	 * 
	 */
	private static void m1() {
		StringBuffer sb=null;
		try {
			sb.append("aa");
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}


重构获取异常栈信息--printStackTrace,布布扣,bubuko.com

重构获取异常栈信息--printStackTrace

标签:重构   异常栈信息   

原文地址:http://blog.csdn.net/wobendiankun/article/details/38444675

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!