用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);
            }
        }
    }



你可能感兴趣的:(c,exception,String,null,Class,float)