我想捕獲攔截器拋出的例外,我該怎么做?
使用 autofac6.0.0,.NET 6
控制器>命令方面>命令
Interceptor 可以從 Command 捕獲例外,但 Controller 不會從 Interceptor 捕獲例外。
登記
builder.RegisterModule<AutofacScanningModule>();
builder.RegisterType<CommandAspect>();
自動傳真掃描模塊
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);
}
}
命令方面
public class CommandAspect : IInterceptor
{
public CommandAspect()
{
}
public async void Intercept(IInvocation invocation)
{
try
{
invocation.Proceed();
}
catch (Exception ex)
{
//Log Output
throw;
}
}
}
網路控制器
try
{
type commandType = typeof(CommandClass);
object commandObject = _serviceProvider.GetService(commandType);
commandType.GetMethod("SomeCommand").Invoke(commandObject);
}
catch(Exception ex)
{
//not handled
}
命令
public class CommandClass : ICommand
{
public virtual void SomeCommand()
{
throw new Exception();
}
}
例外堆疊跟蹤
Unhandled exception. System.Exception: Exception of type 'System.Exception' was thrown.
at Sample.SomeCommand.Find(Record record) SomeCommand.cs:line 42
at Castle.Proxies.SomeCommandProxy.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()
已解決
public class CommandAspect : IInterceptor
{
public CommandAspect()
{
}
public void Intercept(IInvocation invocation)
{
ProcessInterceptAsync(invocation).Wait();
}
private async Task ProcessInterceptAsync(IInvocation invocation)
{
try
{
var proceed = invocation.CaptureProceedInfo();
proceed.Invoke();
}
catch (Exception ex)
{
//Log Output
throw;
}
}
}
uj5u.com熱心網友回復:
您沒有正確進行異步攔截。你必須回傳void從Intercept并設定ReturnValue為Task結果。請參閱此處的檔案。.
您的堆疊跟蹤顯示來自不同執行緒的例外,因此它沒有被捕獲。如果您正確設定了攔截器,我敢打賭它會按預期作業。
uj5u.com熱心網友回復:
您可以實作一個ErrorHandling中間件來處理這個問題。由于中間件在控制器之外運行,因此控制器不會看到錯誤。
看看這個鏈接:https : //docs.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-6.0
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/369946.html
