【发布时间】:2021-02-04 21:46:28
【问题描述】:
我正在为我的 React 前端应用程序开发一个 ASP.NET Core 3.1 API。
我的问题是我的异常并没有像我预期的那样通过我的对象层次结构传播。我认为这可能是由于一些多线程问题,但我对 C# 的了解不够肯定!我正在学习 Pluralsight,但我目前正在学习网络,这对我没有帮助!
调用代码是一个 SignalR Hub 方法,如下所示:
public async Task<bool> UpdateProfile(object profileDto)
{
try
{
ProfileDTO profile = ((JsonElement) profileDto).ToObject<ProfileDTO>();
_profile.UpdateProfile(profile);
return true;
}
catch (Exception e)
{
return false;
}
}
我希望_profile.UpdateProfile(profile); 中抛出或未处理的任何异常都会导致此处的异常块返回 false。我的UpdateProfile() 看起来像这样:
public void UpdateProfile(ProfileDTO profileDto)
{
_databaseService.ExecuteInTransaction(async session =>
{
// simulate an error
throw new Exception("Some exception");
});
}
...我的ExecuteInTransaction() 看起来像这样:
public async void ExecuteInTransaction(Func<IClientSessionHandle, Task> databaseAction)
{
using var session = await Client.StartSessionAsync();
try
{
session.StartTransaction();
await databaseAction(session);
await session.CommitTransactionAsync();
}
catch(Exception e)
{
await session.AbortTransactionAsync();
throw e;
}
}
我希望UpdateProfile() 中引发的异常会逐渐传播到ExecuteInTransaction() 中的catch 块——它确实如此——但更进一步,我希望这个异常会传播到集线器UpdateProfile() 方法。相反,它最终出现在 System.Runtime.ExceptionServices 命名空间中的 ExceptionDispatchInfo 类的 Throw() 方法中。
阅读此文件中的 cmets 让我觉得这是一个线程问题,但我对 C# 中的线程如何工作还不够了解。 UpdateProfile() 中抛出的异常是否有可能达到我的 Hub UpdateProfile() 的顶层? (刚刚注意到它们的名字相同令人困惑)。
【问题讨论】:
-
附带说明,请使用
throw;,而不是throw e;,这样您就不会在异常中丢失原始调用堆栈。 -
Gotchya,好的,谢谢。
标签: c# asp.net multithreading exception