简体   繁体   English

C#尝试/捕获无法按预期工作

[英]C# try/catch not working as expected

I am working on a console app for daily imports into our CMS from a parent ERP system. 我正在开发一个控制台应用程序,用于每天从父ERP系统导入到我们的CMS。 I am having a funky issue with try/catch blocks. 我在try / catch块中遇到了一个时髦的问题。 Errors are happening inside my try's and not making it to the catch. 我尝试的过程中发生了错误,但没有发现问题。 At first, it did go into the catch and I was able to figure out the issue, but now it's just erroring on the try and staying there. 最初,它确实引起了人们的注意,并且我能够找出问题所在,但现在只是尝试并停留在这里而出错。 Hitting continue doesn't work, just keeps showing the error again and again. 击中continue无效,只是不断显示错误一次。 The error has to do with EF and one of the models not having a required field... 该错误与EF和其中一个模型没有必填字段有关...

     public void Save()
    {
        try
        {
            _context.SaveChanges(); <--bombs here and never lets me step thru
        }
        catch (DbEntityValidationException e)
        {
            foreach (var eve in e.EntityValidationErrors)
            {
                Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                    eve.Entry.Entity.GetType().Name, eve.Entry.State);
                foreach (var ve in eve.ValidationErrors)
                {
                    Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                        ve.PropertyName, ve.ErrorMessage);
                }
            }
            throw;
        }
    }

It is probably throwing more or a different exception. 它可能引发更多或不同的异常。 Try using 尝试使用

catch (Exception e)

And see if it now enters the catch and log your exception to know exactly what you are getting 看看它现在是否进入陷阱并记录您的异常以确切地知道您得到了什么

I think it might be a combination of visual studio debugging settings and the fact that there is another type of exception (not found on inheritance hierarchy under DbEntityValidationException). 我认为这可能是Visual Studio调试设置与存在另一种异常(在DbEntityValidationException下的继承层次结构中找不到)的事实的结合。

Please try to handle using a more general exception, even use: 请尝试使用更一般的异常来处理,甚至使用:

catch (Exception ex)

Note: if your debugger just stops in a place where an error occured, you might find this link usefull: https://msdn.microsoft.com/en-us/library/d14azbfh.aspx 注意:如果调试器仅在发生错误的地方停止,则可能会发现此链接有用: https : //msdn.microsoft.com/zh-cn/library/d14azbfh.aspx

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

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