用PostSharp来做异常处理

代码如下:

 class Program
    {
        static void Main(string[] args)
        {
            string filePath = @"C:\log.txt";

            Trace.Listeners.Add(new LogTraceListener(filePath));
            Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));

            MyClass my = new MyClass();
            int ret = my.MyMethod(44, "asdf qwer 1234", 3.14f, true);
            Console.WriteLine(ret.ToString());
            Console.ReadKey();
        }
    }
    public class MyClass
    {
        public MyClass()
        {
        }
#if DEBUG
        [HandleException]
#endif
        public int MyMethod(int x, string someString, float anotherFloat, bool theBool)
        {
            int b = 0;
            int a = 5 / b;
            return x + 1;
        }
    }
    [Serializable]
    public class HandleExceptionAttribute : MethodInterceptionAspect
    {
        public override void OnInvoke(MethodInterceptionArgs args)
        {
            try
            {
                base.OnInvoke(args);
            }
            catch (Exception ex)
            {
                Trace.WriteLine(string.Format("{2}----Entering {0}.{1}.", args.Method.DeclaringType.Name,
                    args.Method.Name, DateTime.Now.ToString()));
                Trace.WriteLine("参数信息");
                for (int x = 0; x < args.Arguments.Count; x++)
                {
                    Trace.WriteLine(args.Method.GetParameters()[x].Name + " = " + args.Arguments.GetArgument(x));
                }
                Trace.WriteLine("ReturnValue=" + args.ReturnValue);
                Trace.WriteLine("异常信息:");
                while (null != ex)
                {
                    Trace.WriteLine("Message=" + ex.Message);
                    Trace.WriteLine("StackTrace=" + ex.StackTrace);
                    ex = ex.InnerException;
                }

            }
        }
    }

    public sealed class LogTraceListener : TraceListener
    {
        public string FileName { set; get; }
        public LogTraceListener(string filename)
        {
            if (File.Exists(filename))
            {
                FileStream fs = File.Create(filename);
                fs.Close();
            }
            FileName = filename;
        }
        public override void Write(string message)
        {
            using (StreamWriter sw = new StreamWriter(FileName, true, Encoding.UTF8, Int16.MaxValue))
            {
                sw.Write(message);
            }
        }

        public override void WriteLine(string message)
        {
            using (StreamWriter sw = new StreamWriter(FileName, true, Encoding.UTF8, Int16.MaxValue))
            {
                sw.WriteLine(message);
            }
        }
    }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值