一、自定义异常类
///
/// 自定义异常
///
[Serializable()]
public class SelException : System.Exception
{
private SelErrorType _selErrorType;
public SelErrorType selErrorType
{
get
{
return _selErrorType;
}
}
private SelLogLevel _selLogLevel;
public SelLogLevel selLogLevel
{
get
{
return _selLogLevel;
}
}
public SelException() : base() { }
public SelException(string message) : base(message) { }
public SelException(string message, System.Exception inner) : base(message, inner) { }
protected SelException(System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context) { }
public SelException(SelErrorType ErrorType, SelLogLevel logLevel, string message)
: base(message)
{
_elErrorType = ErrorType;
_elLogLevel = logLevel;
}
}
二、异常类型
public enum SelErrorType
{
Error_Unknow,
Error_Data_UnKnow,
Error_Date_Type,
Error_Data_Uploading,
}
三、异常级别
public enum SelLogLevel
{
Log_Information,
Log_Debug,
Log_Error,
}
四、定义异常统一处理接口类
class FrmCommons
{
///
/// 异常统一处理
///
///
///
public static void SelExceptionHandle(object sender, ThreadExceptionEventArgs e)
{
try
{
if (typeof(SelException) == e.Exception.GetType())
{
SelException selEx = e.Exception as SelException;
if (selEx.selLogLevel >= SelLogLevel.Log_Information)
{
WriteSelExLog(selEx);
}
MsgBox.Error(Resources.ResourceManager.GetString(selEx.selErrorType.ToString(), Resources.Culture));
}
else
{
WriteSelExLog(e.Exception);
MsgBox.Error(e.Exception.Message);
}
}
catch (Exception ex)
{
}
}
public static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
try
{
if (typeof(SelException) == e.GetType())
{
SelException selEx = e.ExceptionObject as SelException;
if (selEx.selLogLevel >= SelLogLevel.Log_Information)
{
WriteSelExLog(selEx);
}
MsgBox.Error(Resources.ResourceManager.GetString(selEx.selErrorType.ToString(), Resources.Culture));
}
else if (typeof(InvalidOperationException) == e.ExceptionObject.GetType())
{
WriteSelExLog(e.ExceptionObject as InvalidOperationException);
}
else
{
WriteSelExLog(e.ExceptionObject as Exception);
}
}
catch (Exception ex)
{
}
}
private static void WriteSelExLog(Exception ex)
{
//将异常写入日志
string errorMsg = ex.Message + Environment.NewLine + “\t Stack Trace:” + Environment.NewLine + “\t”;
string strTmp = ex.StackTrace.Replace(“\n”,“\n\t”);
errorMsg += strTmp;
Thread t = new Thread(new ParameterizedThreadStart(LogHelper.WriteLog));
t.Start(errorMsg);
}
}
五、入口main函数中注册异常触发事件
1、在发生未捕获线程异常时
Application.ThreadException += new ThreadExceptionEventHandler(FrmCommons.SelExceptionHandle);
2、在某个异常未被捕获时出现
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(FrmCommons.CurrentDomain_UnhandledException);
转载:https://blog.csdn.net/weixin_48408892/article/details/127904001