自定义异常

来源:互联网 发布:淘宝达人互粉平台 编辑:程序博客网 时间:2024/04/28 05:20
 这个非常简单只说两点:1.利用StackFrame来简化错误信息的生成 2.利用自定义异常来简化信息传递.
public class BException : ApplicationException
    
{
        
string _errMsg = "";
        
public BException() : base() {}

        
public BException(string msg) : base(msg) this._errMsg = msg; }

        
public string Message
        
{
            
get return this._errMsg; }
        }


        
public static BException CreateError(string msg)
        
{
            StackTrace st 
= new StackTrace();
            StackFrame sf 
= st.GetFrame(1);            
            MethodBase mi 
= sf.GetMethod();
            Type t 
= mi.DeclaringType;
            
return new BException(string.Format("Error in {0}::{1} -- {2}"
                                                            t.Name, mi.Name, msg));
        }
        
        
        
public override string ToString()
        
{
            
return this._errMsg;
        }

    }
在CreateError方法中利用StackTrace找出调用CreateError的调用者,GetFrame(1).GetFrame(0)就是当前的CreateError方法.是不是很方便.
    Exception还能简化函数调用中的消息传递.例如我们写程序经常会有"用户密码错误","该用户没有权限"这样的消息提示.我们要么是通过判断方法的返回值的方式,要么是通过参数将提示信息返出来.这两种方式不但麻烦而且调用者还需要记得各个方法返回的涵义.而用Exception是一种较好的方法来解决这个问题把需要提示的信息throw出来,然后统一拦截这个自定义消息进行提示.这里以Asp.net来说明统一处理自定义错误:
 
protected override void OnError(EventArgs e) 
        
{
            BException msg 
= Server.GetLastError().GetBaseException() as BException;
            
if(ex != null)
            
{
                
//go(-1)是在提示消息后能够返回到上一个提交页面
                Response.Write("<script>alert('"+msg.Message+"');window.history.go(-1);</script>");
                
//没有这句消息提示会有误
                Server.ClearError();

                
return;
            }

        }
原创粉丝点击