简体   繁体   English

如何处理 C# 中的拦截器抛出的异常

[英]How do I handle Exception throw by Intercepter in C#

I want to Catch the exceptions thrown by Interceptor, how can I do it?我想捕捉拦截器抛出的异常,我该怎么做?

using autofac6.0.0,.NET 6使用 autofac6.0.0,.NET 6

Controller>CommandAspect>Commands控制器>CommandAspect>命令

The Interceptor can catch Exceptions from Command, but the Controller does not catch Exceptions from the Interceptor.拦截器可以从命令中捕获异常,但 Controller 不会从拦截器中捕获异常。

register登记

builder.RegisterModule<AutofacScanningModule>();
builder.RegisterType<CommandAspect>();

AutofacScanningModule AutofacScanning模块

public class AutofacScanningModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {

        var assemblies = AppDomain.CurrentDomain.GetAssemblies();
        builder
            .RegisterAssemblyTypes(assemblies)
            .Where(t => t.GetInterfaces().Any(i => i.IsAssignableFrom(typeof(ICommand))))
            .EnableClassInterceptors()
            .InterceptedBy(typeof(CommandAspect)); 
        base.Load(builder);
    }
}

CommandAspect命令方面

 public class CommandAspect : IInterceptor
{
    public CommandAspect()
    {
    }
    public async void Intercept(IInvocation invocation)
    {
        try
        {
            invocation.Proceed();
        }
        catch (Exception ex)
        {
            //Log Output
            throw;
        }
    }
}

WebController网络控制器

try
{
    type commandType = typeof(CommandClass);
    object commandObject = _serviceProvider.GetService(commandType);
    commandType.GetMethod("SomeCommand").Invoke(commandObject);
}
catch(Exception ex)
{
   //not handled
}

Command命令

 public class CommandClass : ICommand
 {
     public virtual void SomeCommand()
     {
       throw new Exception();
     }
  }

Exception StackTrace异常堆栈跟踪

Unhandled exception. System.Exception: Exception of type 'System.Exception' was thrown.
   at Sample.SomeCommand.Find(Record record) SomeCommand.cs:line 42
   at Castle.Proxies.UserCommandProxy.Find_callback(Record record)
   at Castle.Proxies.Invocations.SomeCommand_Find.InvokeMethodOnTarget()
   at Castle.DynamicProxy.AbstractInvocation.Proceed()
   at Sample.CommandAspect.Intercept(IInvocation invocation) CommandAspect.cs:line 29
   at System.Threading.Tasks.Task.<>c.<ThrowAsync>b__127_1(Object state)
   at System.Threading.QueueUserWorkItemCallback.<>c.<.cctor>b__6_0(QueueUserWorkItemCallback quwi)
   at System.Threading.ExecutionContext.RunForThreadPoolUnsafe[TState](ExecutionContext executionContext, Action`1 callb
ack, TState& state)
   at System.Threading.QueueUserWorkItemCallback.Execute()
   at System.Threading.ThreadPoolWorkQueue.Dispatch()
   at System.Threading.PortableThreadPool.WorkerThread.WorkerThreadStart()
   at System.Threading.Thread.StartCallback()

You can implement an ErrorHandling middleware to handle this.您可以实现一个ErrorHandling中间件来处理这个问题。 Since middleware is acting outside the controller, the controller doesn't get to see the error.由于中间件在 controller 之外运行,因此 controller 不会看到错误。

Have a look at this link: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-6.0看看这个链接: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-6.0

I was able to do what I wanted with the following Code.我能够用下面的代码做我想做的事。 Thank you very much.非常感谢。

 public class CommandAspect : IInterceptor
{
    public CommandAspect()
    {
    }
    public async void Intercept(IInvocation invocation)
    {
        try
        {
            invocation.Proceed();
        }
        catch (Exception ex)
        {
            //Log Output
            invocation.ReturnValue=ex;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM