在控制台应用程序上的异常处理异步代码

发布于 2025-02-12 19:19:20 字数 2881 浏览 0 评论 0原文

希望有人能够将我指向正确的方向。我有一个使用异步方法调用的控制台应用程序,并且在尝试/捕获错误块上遇到了一些麻烦。基本上,当触发触发时,它将在捕获量中执行记录代码,但仍将错误丢给顶级并终止应用程序的整体执行。

我一直在查看有关此问题的其他疑问,从我看过这种行为的情况下,我可能是由异步无效的或没有等待的异步任务引起的。看我的代码,我认为我都没有,所以我有点困难。

引入的错误是缺少连接字符串(在上下文文件中,未显示),该字符串应在PayloadRepo方法中抛出处理的异常。逐步浏览调试器,此错误确实被捕获和记录为预期的,但是它似乎仍然会恢复到主要方法,并导致整体执行破裂。

谁能发现可能发生的事情?

谢谢你!

    static async Task Main(string[] args)
    {
        BuildLogConfiguration();
        BuildDependencyContainer();

        await RunProgram();
    }

    static async Task RunProgram()
    {
        systemLog.Info("Started full process at: " + System.DateTime.Now);

        using (var scope = Container.BeginLifetimeScope())
        {
            var payloadService = scope.Resolve<IPayloadService>();
            await payloadService.ProcessPayloadData(scope);
        }

        systemLog.Info("Completing full process at: " + System.DateTime.Now);
    }

    public class PayloadService : IPayloadService
    {
        private static readonly ILog _systemLog = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        public async Task ProcessPayloadData(ILifetimeScope scope)
        {
            await PayloadData_Process(scope);
        }

        private async Task PayloadData_Process(ILifetimeScope scope)
        {
            var repo = scope.Resolve<IPayloadRepo>();

            var payloadList = await repo.Payload_Get();
        }
    }

    public class PayloadRepo : IPayloadRepo
    {
        public async Task<IEnumerable<Payload>> Payload_Get()
        {
            using (var context = new ASGB_DataLayerContext())
            {
                try
                {
                    var payloadList = context.Payloads;

                    var result = await payloadList.ToListAsync();

                    return result;
                }
                catch (Exception ex) <<--- CATCHES THIS AND EXECUTES CODE WITHIN, BUT IT STILL THROWS AN ERROR ON RunProgram().Wait() AND TERMINATES PROGRAM
                {
                    systemLog.Error(ex.Message);
                    systemLog.Error(ex.InnerException);
                    var entries = context.ChangeTracker.Entries().Where(e => e.State != EntityState.Unchanged);
                    foreach (var entry in entries)
                    {
                        foreach (var prop in entry.CurrentValues.Properties)
                        {
                            var val = prop.PropertyInfo.GetValue(entry.Entity);
                            systemLog.Error($"{prop.ToString()} ~ ({val?.ToString().Length})({val})");
                        }
                    }
                    systemLog.Error("------------------------------------------------------------------------");

                    return null;
                }
            }
        }
   }

Hoping that someone will be able to point me in the right direction. I have a console application that uses async method calls and I'm having a bit of trouble with the try/catch error blocks. Basically, when a catch is triggered it executes the logging code within the catch but it still throws the error up to the top level and terminates the overall execution of the app.

I've been looking through other queries about this and from what I've seen this type of behaviour can be caused by either an async void or an async Task with no await. Looking at my code I don't think I have either so I'm a bit stumped.

The error being introduced is a missing connection string (in the context file, not shown), which should throw a handled exception in the PayloadRepo method. Stepping through the debugger this error is indeed caught and logged as expected, however it still seems to bubble back up to the Main method and cause the overall execution to break.

Can anyone spot what may be happening?

Thank you!

    static async Task Main(string[] args)
    {
        BuildLogConfiguration();
        BuildDependencyContainer();

        await RunProgram();
    }

    static async Task RunProgram()
    {
        systemLog.Info("Started full process at: " + System.DateTime.Now);

        using (var scope = Container.BeginLifetimeScope())
        {
            var payloadService = scope.Resolve<IPayloadService>();
            await payloadService.ProcessPayloadData(scope);
        }

        systemLog.Info("Completing full process at: " + System.DateTime.Now);
    }

    public class PayloadService : IPayloadService
    {
        private static readonly ILog _systemLog = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        public async Task ProcessPayloadData(ILifetimeScope scope)
        {
            await PayloadData_Process(scope);
        }

        private async Task PayloadData_Process(ILifetimeScope scope)
        {
            var repo = scope.Resolve<IPayloadRepo>();

            var payloadList = await repo.Payload_Get();
        }
    }

    public class PayloadRepo : IPayloadRepo
    {
        public async Task<IEnumerable<Payload>> Payload_Get()
        {
            using (var context = new ASGB_DataLayerContext())
            {
                try
                {
                    var payloadList = context.Payloads;

                    var result = await payloadList.ToListAsync();

                    return result;
                }
                catch (Exception ex) <<--- CATCHES THIS AND EXECUTES CODE WITHIN, BUT IT STILL THROWS AN ERROR ON RunProgram().Wait() AND TERMINATES PROGRAM
                {
                    systemLog.Error(ex.Message);
                    systemLog.Error(ex.InnerException);
                    var entries = context.ChangeTracker.Entries().Where(e => e.State != EntityState.Unchanged);
                    foreach (var entry in entries)
                    {
                        foreach (var prop in entry.CurrentValues.Properties)
                        {
                            var val = prop.PropertyInfo.GetValue(entry.Entity);
                            systemLog.Error(
quot;{prop.ToString()} ~ ({val?.ToString().Length})({val})");
                        }
                    }
                    systemLog.Error("------------------------------------------------------------------------");

                    return null;
                }
            }
        }
   }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文