异常拦截器(ExceptionInterceptor)


 

1.异常拦截器(ExceptionInterceptor):

 

实现了 Castle 的 IInterceptor 接口

在 Intercept 方法中通过 try-catch 块捕获目标方法执行过程中的异常

可以针对不同类型的异常进行特定处理

包含异常日志记录功能,记录发生异常的方法、参数等信息

 

 1 using Castle.DynamicProxy;
 2 using System;
 3 
 4 /// <summary>
 5 /// 异常处理拦截器
 6 /// </summary>
 7 public class ExceptionInterceptor : IInterceptor
 8 {
 9     public void Intercept(IInvocation invocation)
10     {
11         try
12         {
13             // 执行目标方法
14             invocation.Proceed();
15         }
16         catch (ArgumentNullException ex)
17         {
18             // 处理特定类型的异常
19             Console.WriteLine($"参数为空异常: {ex.Message}");
20             // 可以根据需要重新抛出异常或设置返回值
21             // throw;
22         }
23         catch (InvalidOperationException ex)
24         {
25             Console.WriteLine($"操作无效异常: {ex.Message}");
26         }
27         catch (Exception ex)
28         {
29             // 处理通用异常
30             Console.WriteLine($"发生未处理异常: {ex.Message}");
31             // 记录异常详细信息
32             LogException(ex, invocation);
33         }
34     }
35 
36     /// <summary>
37     /// 记录异常详细信息
38     /// </summary>
39     private void LogException(Exception ex, IInvocation invocation)
40     {
41         string message = $"方法: {invocation.Method.Name}\n" +
42                          $"参数: {string.Join(", ", invocation.Arguments)}\n" +
43                          $"异常: {ex}\n";
44         
45         // 实际应用中可以写入日志文件或日志系统
46         Console.WriteLine($"异常日志:\n{message}");
47     }
48 }
View Code

 

 

2.服务代理工厂(ServiceProxyFactory):

 

使用 ProxyGenerator 创建代理对象

将拦截器应用到目标对象上

提供简洁的接口用于创建带有拦截功能的服务实例

 1 using Castle.DynamicProxy;
 2 using System;
 3 
 4 /// <summary>
 5 /// 服务代理工厂,用于创建带有拦截器的服务实例
 6 /// </summary>
 7 public static class ServiceProxyFactory
 8 {
 9     private static readonly ProxyGenerator _proxyGenerator = new ProxyGenerator();
10     
11     /// <summary>
12     /// 创建带有异常拦截器的服务实例
13     /// </summary>
14     public static T Create<T>(T target) where T : class
15     {
16         if (target == null)
17             throw new ArgumentNullException(nameof(target));
18             
19         // 创建拦截器
20         var interceptor = new ExceptionInterceptor();
21         
22         // 生成代理对象
23         return _proxyGenerator.CreateInterfaceProxyWithTarget(
24             typeof(T), 
25             target, 
26             interceptor) as T;
27     }
28 }
View Code

 

3.使用方式:

 

定义业务接口和实现类

通过代理工厂创建代理对象

调用代理对象的方法,异常会被自动拦截处理

 1 using System;
 2 
 3 // 定义服务接口
 4 public interface IOrderService
 5 {
 6     void CreateOrder(int orderId, string customerName);
 7     decimal CalculateTotal(decimal price, int quantity);
 8 }
 9 
10 // 实现服务
11 public class OrderService : IOrderService
12 {
13     public void CreateOrder(int orderId, string customerName)
14     {
15         if (orderId <= 0)
16             throw new ArgumentException("订单ID必须大于0", nameof(orderId));
17             
18         if (string.IsNullOrEmpty(customerName))
19             throw new ArgumentNullException(nameof(customerName), "客户名称不能为空");
20             
21         Console.WriteLine($"订单 {orderId} 创建成功,客户: {customerName}");
22     }
23     
24     public decimal CalculateTotal(decimal price, int quantity)
25     {
26         if (price < 0)
27             throw new InvalidOperationException("价格不能为负数");
28             
29         if (quantity <= 0)
30             throw new ArgumentOutOfRangeException(nameof(quantity), "数量必须大于0");
31             
32         return price * quantity;
33     }
34 }
35 
36 // 使用示例
37 class Program
38 {
39     static void Main(string[] args)
40     {
41         // 创建原始服务实例
42         IOrderService originalService = new OrderService();
43         
44         // 创建带有异常拦截的代理服务
45         IOrderService proxyService = ServiceProxyFactory.Create(originalService);
46         
47         try
48         {
49             // 测试正常情况
50             proxyService.CreateOrder(1001, "张三");
51             
52             // 测试异常情况
53             proxyService.CreateOrder(-1, null);
54             proxyService.CalculateTotal(-100, 5);
55         }
56         catch (Exception ex)
57         {
58             Console.WriteLine($"Main方法捕获到异常: {ex.Message}");
59         }
60     }
61 }
View Code

 

posted @ 2025-08-27 23:00  小码哥-风云  阅读(5)  评论(0)    收藏  举报