1. 程式人生 > >java:獲取異常的堆疊資訊

java:獲取異常的堆疊資訊

做的java開發的時候,經常會遇到程式碼拋異常後,需要把異常資訊儲存到資料庫或者上傳到雲伺服器做快取分析。這時候就需要獲取異常的堆疊資訊(詳細錯誤資訊)。

人有的用e.getMessage()來電子雜誌異常資訊,但是這樣獲取到的資訊內容並不全,而且有時候為空。我們可以用下面方法來獲取。

   public static String getStackTrace(Throwable throwable)
    {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);

        try
{ throwable.printStackTrace(pw); return sw.toString(); } finally { pw.close(); } }

使用也很簡單:

  public static void test()
    {
        try
        {
            int i = 0;
            int m = 10 / i;
        } catch (Exception e)
        {
            System.out
.println(e.getMessage()); System.out.println("------調皮的分割線------"); System.out.println(ExceptionUtil.getStackTrace(e)); } }

也可以放在request中:

  request.setAttribute(“errorCode1”,getStackTrace(e));
  logger.error(e.getMessage(),e);

我們看下列印結果: 

這裡寫圖片描述

以下是專案中配置的相關資訊:

1、在web.xml中新增攔截器:在執行方法前後攔截,如果出現異常捕獲並放入request中

  <filter>
    <filter-name>initContextFilter</filter-name>
    <filter-class>
      com.hys.framework.web.filter.InitContextFilter
    </filter-class>
    <init-param>
      <param-name>RequestEncoding</param-name>
      <param-value>utf-8</param-value>
    </init-param>
    <init-param>
      <param-name>ResponseEncoding</param-name>
      <param-value>utf-8</param-value>
    </init-param>
    <init-param>
      <param-name>FailureForwardName</param-name>
      <param-value>/commons/failure.jsp</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>initContextFilter</filter-name>
    <url-pattern>*.do</url-pattern>
  </filter-mapping>

2、攔截器類(稍後新增)

3、異常錯誤頁面:fail.jsp

<%@	page contentType="text/html;charset=utf-8"%>
<!DOCTYPE HTML>
<html>
	<head>
	<%@ include file="/commons/taglibs.jsp"%>
		<title>Failure</title>
		<link href="${ctx}/css/style1.css" type=text/css rel=stylesheet>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<script type="text/javascript">
			function forback()
			{
				if(window.history.length==0)
				{
					window.close();
				}
				else
				{
					window.history.back();
				}
			}
	</script>
		<style type="text/css">
#Error {
	COLOR: #B22222;
	FONT-SIZE: 14px;
}
</style>
	</head>
	<body leftmargin="0" topmargin="0" class="body1">
		<center>
			<TABLE width="100%" height="600" border="0" cellPadding="0"
				cellSpacing="0">
				<tr>
					<td align="center">
						<table width="70%" border="0" cellpadding="1" cellspacing="0"
							bordercolor="#BDC7D6" bgcolor="#BDC7D6">
							<tr>
								<td>
									<table width="100%" border="0" cellpadding="0" cellspacing="0"
										bordercolor="#BDC7D6" bgcolor="#FFFFFF" class="lankuang1">
										<tr>
											<td height="25" align="left" valign="middle"
												bgcolor="#EFF3F7" class="lanbottom">
												<strong style="color: #5F9EA0">報錯提醒:${ErrorMsg }</strong>
											</td>
										</tr>
										<tr>
											<td height="120" align="center">
												<table width="90%" border="0" cellspacing="0"
													cellpadding="0">
													<tr>
														<td width="73%" align="left" valign="middle">
															<span onclick="showError()" style="cursor:pointer">出錯了,請聯絡管理員!</span>
														</td>
													</tr>
													<tr>
														<td colspan="2" align="center">
															<input type="button" name="forward" value="返回  "
																class="but2" onClick="forback();">
														</td>
													</tr>
												</table>
											</td>
										</tr>
									</table>
								</td>
							</tr>
						</table>
					</td>
				</tr>
			</TABLE>
						</center>
													<div style="display:none" id="errorcode">
														<span id="Error">資訊:${msg }</span>
														<br/>
														---------------------------------
														堆疊:
														${stack }
														-----------
													</div>
	
	</body>
	<script type="text/javascript">
		function showError(){
			document.getElementById("errorcode").style.display="block";
		}
	</script>
</html>

最後效果: