C# 自定义异常 实现日志记录通用功能
我想做个自定义的异常基类,首先肯定是要实现相关的4个构造函数,对吧。但是我想做到另外一个功能,
可以选择性的实现日志记录的功能。在这个基类中如何实现?本人菜鸟,求高手指点。
public class ParaException : ApplicationException//由用户程序引发,用于派生自定义的异常类型 { /// <summary> /// 默认构造函数 /// </summary> public ParaException() { } public ParaException(string message) : base(message) { } public ParaException(string message, Exception inner) : base(message, inner) { } public ParaException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } }
try { //some code } catch (ParaException ex) { ex.WriteLog(ex.Message); }
[解决办法]
namespace ESWS{ using System; using System.IO; using System.Text; using System.Threading; internal sealed class CustomException : Exception { private string errorMessage; private string methodName; private string stackTrace; internal CustomException() { } internal CustomException(string errorMessage) : base(errorMessage) { } internal CustomException(string errorMessage, Exception innerException) : base(errorMessage, innerException) { this.methodName = innerException.TargetSite.Name; this.errorMessage = errorMessage; this.stackTrace = innerException.StackTrace; new Thread(new ThreadStart(this.WriteLog)).Start(); } public override Exception GetBaseException() { return this; } public override string ToString() { return base.GetType().FullName; } private void WriteLog() { this.WriteLog(this.methodName, this.errorMessage, this.stackTrace); } private void WriteLog(string methodName, string errorMessage, string stackTrace) { try { string str = string.Format(@"{0}\Log", Global.MainDirectoryName); string path = string.Format(@"{0}\{1}→{2}.log", str, methodName, DateTime.Now.ToString("yyyy-MM-dd HH")); if (!Directory.Exists(str)) { Directory.CreateDirectory(str); } using (FileStream stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite)) { string s = string.Concat(new object[] { "输出时间:", DateTime.Now, Environment.NewLine, " → 输出信息:", errorMessage, Environment.NewLine, " → 堆栈信息:", stackTrace, Environment.NewLine, Environment.NewLine }); byte[] bytes = Encoding.UTF8.GetBytes(s); stream.Write(bytes, 0, bytes.Length); } } catch (IOException exception) { throw new IOException(exception.Message, exception); } } }}
[解决办法]