近日给老美做外包项目,被老美逼出来了一套关于错误处理的方法,在此不敢藏拙,奉献出来给大家批判。
首先,屏蔽程序中所有的自动错误处理,千万不要出来:“
System.Web.Services.Protocols.SoapException: System.Web.Services.Protocols.SoapException: 服务器无法处理请求。”等错误页面,而应该是一些简单易懂的东西,俺在此使用的是Duwamish 7.0里的错误处理页面:
<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>
当然,要做到这一点也很简单,可以在web.config里这样配置(假如你的错误页面叫Error.aspx):
<customErrors
defaultRedirect = "Error.aspx"
mode="On"
/>
这个配置你可以给据你的需要修改(比如mode的值)。
其次,要把错误信息写到日志中去。
我们定义错误日志信息的结构如下
public struct ErrorLogItem
{
public string User ;//当前登录人
public string AppName ;//应用程序名称
public string ClassName ;//错误发生的类名称
public string FunctionName ;//错误发生的方法(事件)名称
public string Position ;//错误的位置(或其它信息)
public string ErrorInfo ;//错误信息
public DateTime OccurTime ;//错误发生的时间
}
错误日志类如下所示:
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
我们可以通过调用SetErrorLog方法来把信息写到日志中去。
当然,日志的位置以及日志记录错误信息的数量也是可以配置的
<appSettings>
<add key="errlogfile" value="c:\ddmsLog.xml" />
<add key="maxerrlogcount" value="1000" />
</appSettings>
我们可以通过下面的方法得到他们的值:
public static string ErrorLogFile
{
get
{
return ConfigurationSettings.AppSettings["errlogfile"].Trim() ;
}
}
public static int MaxErrorLogCount
{
get
{
return int.Parse(ConfigurationSettings.AppSettings["maxerrlogcount"].Trim()) ;
}
}
再次,我们还要把错误信息自动发到我们的信箱中(这一点很重要--至少对我这个项目来说,我不能跑到美国去调试,也不能老是让老外告诉我发生了什么错误)
发送邮件的方法如下:
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 ;
}
意思大家应该明白,里面具体的一些方法调用大家可以写自己的代码来代替。
当然,邮箱地址也是可以配置的:
<appSettings>
<add key="errorlogemail" value="zl3624@china.com" />
</appSettings>
取出方法:
public static string ErrorLogEmail
{
get
{
return ConfigurationSettings.AppSettings["errorlogemail"].Trim() ;
}
}
最后,是用一个方法来调用写日志和发邮件的方法:
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 ;
}
}
呵呵,这样错误处理应该差不多了吧?