自定义一个拦截器
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Interface)] public class UnityAopAttribute : HandlerAttribute, ICallHandler { public override ICallHandler CreateHandler(IUnityContainer container) { return this; } public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { var s = new Stopwatch(); s.Start(); var result = getNext()(input, getNext); if (result.Exception != null) { WriteLog(result.Exception.ToString()); //表示处理异常 Unity就不会抛出 result.Exception = null; } s.Stop(); WriteLog("方法:{0},参数:{1},耗时:{2}", input.MethodBase.Name, JsonConvert.SerializeObject(input.Arguments), s.Elapsed.TotalMilliseconds); return result; } private void WriteLog(string format, params object[] arg) { var path = AppDomain.CurrentDomain.BaseDirectory + "log.txt"; File.AppendAllText(path, string.Format(format, arg) + "\r\n"); } public IEnumerable<Type> GetRequiredInterfaces() { return Type.EmptyTypes; } public bool WillExecute => false; }接口定义如下
public interface IOrderService { string GetOrder(); string GetOrderDetail(); }实现如下
加上UnityAop标记
[UnityAop] public class OrderService : IOrderService { public string GetOrder() { Thread.Sleep(new Random().Next(500, 1000)); return "GetOrder"; } public string GetOrderDetail() { var i = Convert.ToInt32("a"); return i + "GetOrder"; } }注入及调用如下
示例代码:https://github.com/sunven/Abp1
ReferenceUnity AOP 处理异常的方法