近日給老美做外包項(xiàng)目,被老美逼出來(lái)了一套關(guān)于錯(cuò)誤處理的方法,在此不敢藏拙,奉獻(xiàn)出來(lái)給大家批判。
首先,屏蔽程序中所有的自動(dòng)錯(cuò)誤處理,千萬(wàn)不要出來(lái):“ System.Web.Services.Protocols.SoapException: System.Web.Services.Protocols.SoapException: 服務(wù)器無(wú)法處理請(qǐng)求!钡儒e(cuò)誤頁(yè)面,而應(yīng)該是一些簡(jiǎn)單易懂的東西,俺在此使用的是Duwamish 7.0里的錯(cuò)誤處理頁(yè)面: <body > <H2>An error has occurred</H2> <P>We were unable to complete your request. This failure has been logged with our system administrators, who are currently working to resolve the problem. We apologize for any inconvenience caused by this temporary service outage, and we appreciate your patience as we work to improve our web site.</P> </body> 當(dāng)然,要做到這一點(diǎn)也很簡(jiǎn)單,可以在web.config里這樣配置(假如你的錯(cuò)誤頁(yè)面叫Error.aspx): <customErrors defaultRedirect = "Error.aspx" mode="On" /> 這個(gè)配置你可以給據(jù)你的需要修改(比如mode的值)。
其次,要把錯(cuò)誤信息寫(xiě)到日志中去。 我們定義錯(cuò)誤日志信息的結(jié)構(gòu)如下 public struct ErrorLogItem { public string User ;//當(dāng)前登錄人 public string AppName ;//應(yīng)用程序名稱(chēng) public string ClassName ;//錯(cuò)誤發(fā)生的類(lèi)名稱(chēng) public string FunctionName ;//錯(cuò)誤發(fā)生的方法(事件)名稱(chēng) public string Position ;//錯(cuò)誤的位置(或其它信息) public string ErrorInfo ;//錯(cuò)誤信息 public DateTime OccurTime ;//錯(cuò)誤發(fā)生的時(shí)間 }
錯(cuò)誤日志類(lèi)如下所示: public class ErrorLog { private static ErrorLog _Instance = null ; private static string strRootName ; private static XmlElement xmlRoot ; private static XmlDocument xmlDoc ; private ErrorLog() { Load() ; } private bool Load() { if (!File.Exists(AppGlobal.ErrorLogFile)) CreateErrorLogFile(AppGlobal.ErrorLogFile); if (xmlDoc == null) xmlDoc = new XmlDocument() ; try { xmlDoc.Load(AppGlobal.ErrorLogFile) ; } catch { return false ; } xmlRoot = xmlDoc.DocumentElement ; if (xmlRoot != null) strRootName = "/" + xmlRoot.Name + "/" ; return true ; } private void CreateErrorLogFile(string strFileName) { StringBuilder sb = new StringBuilder() ; sb.Append("<?xml version='1.0\' ?> ") ; sb.Append("<errorlog>") ; sb.Append("</errorlog>") ; XmlDocument xmlDoc = new XmlDocument() ; xmlDoc.LoadXml(sb.ToString()) ; xmlDoc.Save(strFileName) ; } private void AddXmlAttribute(XmlElement xNode,string strAttr,string strAttrvalue) { XmlAttribute xAttr = (XmlAttribute)xmlDoc.CreateNode(XmlNodeType.Attribute,strAttr,null) ; xAttr.InnerText = strAttrvalue; xNode.Attributes.Append(xAttr) ; } public void SetErrorLog(ErrorLogItem errItem) { XmlElement xErrorElement = xmlDoc.CreateElement("error") ;
AddXmlAttribute(xErrorElement,"username",errItem.User); AddXmlAttribute(xErrorElement,"application",errItem.AppName); AddXmlAttribute(xErrorElement,"classname",errItem.ClassName); AddXmlAttribute(xErrorElement,"functionname",errItem.FunctionName); AddXmlAttribute(xErrorElement,"position",errItem.Position); AddXmlAttribute(xErrorElement,"occurtime",errItem.OccurTime.ToString("g")); xErrorElement.InnerText = errItem.ErrorInfo ;
xmlRoot.AppendChild(xErrorElement) ; if (xmlRoot.ChildNodes.Count > AppGlobal.MaxErrorLogCount) xmlRoot.RemoveChild(xmlRoot.FirstChild) ; xmlDoc.Save(AppGlobal.ErrorLogFile) ; } public static ErrorLog Instance() { if(_Instance == null) { _Instance = new ErrorLog() ; } return _Instance ; } }//end class
我們可以通過(guò)調(diào)用SetErrorLog方法來(lái)把信息寫(xiě)到日志中去。 當(dāng)然,日志的位置以及日志記錄錯(cuò)誤信息的數(shù)量也是可以配置的 <appSettings> <add key="errlogfile" value="c:\ddmsLog.xml" /> <add key="maxerrlogcount" value="1000" /> </appSettings> 我們可以通過(guò)下面的方法得到他們的值: public static string ErrorLogFile { get { return ConfigurationSettings.AppSettings["errlogfile"].Trim() ; } } public static int MaxErrorLogCount { get { return int.Parse(ConfigurationSettings.AppSettings["maxerrlogcount"].Trim()) ; } }
再次,我們還要把錯(cuò)誤信息自動(dòng)發(fā)到我們的信箱中(這一點(diǎn)很重要--至少對(duì)我這個(gè)項(xiàng)目來(lái)說(shuō),我不能跑到美國(guó)去調(diào)試,也不能老是讓老外告訴我發(fā)生了什么錯(cuò)誤) 發(fā)送郵件的方法如下: public static bool SendErrorLogMail(string StrTo,ErrorLogItem errItem) { MailLink.Load(AppGlobal.MAIL_CFG_FILE_PATH) ;
string StrName = MailLink.GetNodeText(MAILLINKITEM.USERNAME) ; string StrCode = MailLink.GetNodeText(MAILLINKITEM.PASSWORD) ; string strFrom = MailLink.GetNodeText(MAILLINKITEM.MAILFROM) ; string strSubject = "Error Log" ; string strSmtpServer = MailLink.GetNodeText(MAILLINKITEM.MAILSMTPSERVER) ; string strMailBody = "<div>An error occur </div>" ; strMailBody += "<div>Login User:" + errItem.User + "</div>" ; strMailBody += "<div>Applicatin Name:" + errItem.AppName + "</div>" ; strMailBody += "<div>ClassName:" + errItem.ClassName + "</div>" ; strMailBody += "<div>Function Name:" + errItem.FunctionName + "</div>" ; strMailBody += "<div>Error Position:" + errItem.Position + "</div>" ; strMailBody += "<div>Error Information:" + errItem.ErrorInfo + "</div>" ; strMailBody += "<DIV> </DIV>" ; strMailBody += "<DIV> </DIV>" ; strMailBody += "<DIV>" + errItem.OccurTime + "</DIV>" ;
bool blResult = MailLink.SendMail(StrTo,strMailBody,strSubject,strFrom,StrName,StrCode,strSmtpServer) ;
return blResult ; } 意思大家應(yīng)該明白,里面具體的一些方法調(diào)用大家可以寫(xiě)自己的代碼來(lái)代替。 當(dāng)然,郵箱地址也是可以配置的: <appSettings> <add key="errorlogemail" value="zl3624@china.com" /> </appSettings> 取出方法: public static string ErrorLogEmail { get { return ConfigurationSettings.AppSettings["errorlogemail"].Trim() ; } } 最后,是用一個(gè)方法來(lái)調(diào)用寫(xiě)日志和發(fā)郵件的方法: public static void LogAppError(Exception thisErr,string strClass,string strFunc,string strPos,string strUser) { ErrorLogItem errItem = new ErrorLogItem() ; errItem.AppName = "Your AppName" ; errItem.ClassName = strClass ; errItem.ErrorInfo = thisErr.ToString() ; errItem.FunctionName = strFunc ; errItem.OccurTime = DateTime.Now ; errItem.Position = strPos ; errItem.User =strUser ;
try { ErrorLog.Instance().SetErrorLog(errItem) ; SendErrorLogMail(ErrorLogEmail,sb.ToString()) ; } catch { } finally { } throw new Exception("An error occur :"+thisErr.ToString()) ; } 那么,怎樣在程序中捕獲異常哪? 下面是俺的一段代碼: public DataSet GetPrsnInfo(int aiTrx_no,int aiIncid_no,int aiPrsn_id) { try { ddmsWsPInfo.CandiService ddmsCS = new ddmsWsPInfo.CandiService() ; ddmsCS.Url = AppGlobal.WebServicesUrl ; DataSet dsPrsn = ddmsCS.GetPrsnInfo(aiTrx_no,aiIncid_no,aiPrsn_id) ; ddmsCS.Dispose(); return dsPrsn ; } catch(Exception e) { string strErr = "aiTrx_no=" + aiTrx_no + " aiIncid_no=" + aiIncid_no + " aiPrsn_id=" + aiPrsn_id ; AppGlobal.LogAppError(e,"PrsnManager","GetExtraPrsn",strErr,LoginUser.UserID) ; return null ; } }
呵呵,這樣錯(cuò)誤處理應(yīng)該差不多了吧?
|