C/S开发框架系统异常处理机制(Exception Handler)


异常处理机制(Exception Handler)
构建安全稳定的应用系统首先要处理的是系统抛出的异常, 否则在程序运行中因系统发生错误而中止程序。我总结了以下四种保护机制:
1. 处理系统未被捕获的异常, static void Main() 方法内设置
//引发未捕获的异常,这里没有try{}catch()异常保护,
//由Application.ThreadException事件捕获
2.处理界面层抛出的异常
//界面层异常指捕获窗体内的错误。
//常用错误是操作未实例化的对象,索引错误,第三方控件错误等.
3.处理业务逻辑层抛出异常
4. 处理数据层或多层嵌套调用中抛出异常



用户自定义异常:
/// <summary>
/// 用户自定义异常
/// </summary>
public class CustomException : Exception
{
private string MSG = "系统产生用户自定义异常!";
private object _sender = null;
public CustomException(object sender, string msg)
: base(msg)
{
_sender = sender;
}
}
/// <summary>
/// 用户操作未授权的窗体或业务逻辑所产生的异常
/// </summary>
public class UnauthorizedException : CustomException
{
public UnauthorizedException(object sender, string msg)
: base(sender, msg)
{
//
}
}
/// <summary>
/// 用户操作已锁定的单据
/// </summary>
public class OperateLockedOrder : CustomException
{
public OperateLockedOrder(object sender, string msg)
: base(sender, msg)
{
//
}
}
// 来源:www.CSFramework.com, C/S结构框架学习网
/// 用户自定义异常
/// </summary>
public class CustomException : Exception
{
private string MSG = "系统产生用户自定义异常!";
private object _sender = null;
public CustomException(object sender, string msg)
: base(msg)
{
_sender = sender;
}
}
/// <summary>
/// 用户操作未授权的窗体或业务逻辑所产生的异常
/// </summary>
public class UnauthorizedException : CustomException
{
public UnauthorizedException(object sender, string msg)
: base(sender, msg)
{
//
}
}
/// <summary>
/// 用户操作已锁定的单据
/// </summary>
public class OperateLockedOrder : CustomException
{
public OperateLockedOrder(object sender, string msg)
: base(sender, msg)
{
//
}
}
// 来源:www.CSFramework.com, C/S结构框架学习网
/// <summary>
/// 处理系统所产生的异常
/// </summary>
public class ExceptionHandle
{
//处理由sender参数传递过来的异常
public static void Handle(object sender, Exception ex)
{
string msg = "Sender:" sender.GetType().Name ":\r\nException Type:"
ex.GetType().Name "\r\nDescription:" ex.Message;
ExceptionLog.WriteLog(msg "\r\nException Time:" DateTime.Now.ToString());
ExceptionLog.WriteLog("------------------------------------------------------");
_text.Text = msg; //在TextBox控件内显示
MessageBox.Show(msg, "捕获到异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
private static TextBox _text = null;
/// <summary>
/// 这个方法仅用于显示当前异常信息,无实际意义!
/// </summary>
public static void ExceptionTextBox(TextBox text)
{
_text = text;
}
}
// 来源:www.CSFramework.com, C/S结构框架学习网

扫一扫加作者微信


版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
NewDoc C/S框架网