在捕获到某些错误的情况下如何打破循环

发布于 2024-12-25 19:12:32 字数 3229 浏览 6 评论 0原文

问:

如果事件中捕获到一些异常,我想中断循环。

代码:

XmlDocument x = new XmlDocument();
x.Load(targetFileName);

XmlReaderSettings settings = new XmlReaderSettings();
settings.CloseInput = true;
settings.ValidationEventHandler += Handler;

settings.ValidationType = ValidationType.Schema;
settings.Schemas.Add(null,System.Web.HttpContext.Current.Server.MapPath("~/importSchema/IntialSchema.xsd"));
settings.ValidationFlags =
     XmlSchemaValidationFlags.ReportValidationWarnings |
XmlSchemaValidationFlags.ProcessIdentityConstraints |
XmlSchemaValidationFlags.ProcessInlineSchema |
XmlSchemaValidationFlags.ProcessSchemaLocation;

using (StreamReader str_reader = new StreamReader(targetFileName))
{

    using (XmlReader validatingReader = XmlReader.Create(str_reader, settings))
    {
        while (validatingReader.Read())
        {
            //I wanna to break this loop if there is some caught error .
        }
    }
}

private static void Handler(object sender, ValidationEventArgs e)
{

    if (e.Severity == XmlSeverityType.Error || e.Severity == XmlSeverityType.Warning)
    {
        try
        {
            throw new Exception(
                 String.Format("Line: {0}, Position: {1} \"{2}\"",
                     e.Exception.LineNumber, e.Exception.LinePosition, e.Exception.Message));
        }
        catch (Exception ee)
        {
            Common.ErrMappingForInformix.WriteLog(ee.Message);
            ScheduleForm sf = new ScheduleForm();
            sf.ShowStatus("Error,Invalid xml file", "error", "", 1);

        }

    }

}

#编辑1:

XmlDocument x = new XmlDocument();
x.Load(targetFileName);

XmlReaderSettings settings = new XmlReaderSettings();
settings.CloseInput = true;
settings.ValidationEventHandler += (senderValidation, ee) =>
{
    if (ee.Severity == XmlSeverityType.Error || ee.Severity == XmlSeverityType.Warning)
    {
        try
        {
            this.validationFailed = true;
            throw new Exception(
                 String.Format("Line: {0}, Position: {1} \"{2}\"",
                     ee.Exception.LineNumber, ee.Exception.LinePosition, ee.Exception.Message));
        }
        catch (Exception ex)
        {

            Common.ErrMappingForInformix.WriteLog(ex.Message);
            this.ShowStatus("Error", "error", "", 1);
        }

    }
};

settings.ValidationType = ValidationType.Schema;
settings.Schemas.Add(null, System.Web.HttpContext.Current.Server.MapPath("~/importSchema/IntialSchema.xsd"));
settings.ValidationFlags =
     XmlSchemaValidationFlags.ReportValidationWarnings |
XmlSchemaValidationFlags.ProcessIdentityConstraints |
XmlSchemaValidationFlags.ProcessInlineSchema |
XmlSchemaValidationFlags.ProcessSchemaLocation;

using (StreamReader str_reader = new StreamReader(targetFileName))
{

    using (XmlReader validatingReader = XmlReader.Create(str_reader, settings))
    {
        while (validatingReader.Read())
        {
            //Loop through the document
            if (validationFailed)
            {
                break;
            }

        }
    }
}

它打破了循环,但不执行事件处理程序。

Q:

I want to break the loop if some exception has been caught in the event.

The code :

XmlDocument x = new XmlDocument();
x.Load(targetFileName);

XmlReaderSettings settings = new XmlReaderSettings();
settings.CloseInput = true;
settings.ValidationEventHandler += Handler;

settings.ValidationType = ValidationType.Schema;
settings.Schemas.Add(null,System.Web.HttpContext.Current.Server.MapPath("~/importSchema/IntialSchema.xsd"));
settings.ValidationFlags =
     XmlSchemaValidationFlags.ReportValidationWarnings |
XmlSchemaValidationFlags.ProcessIdentityConstraints |
XmlSchemaValidationFlags.ProcessInlineSchema |
XmlSchemaValidationFlags.ProcessSchemaLocation;

using (StreamReader str_reader = new StreamReader(targetFileName))
{

    using (XmlReader validatingReader = XmlReader.Create(str_reader, settings))
    {
        while (validatingReader.Read())
        {
            //I wanna to break this loop if there is some caught error .
        }
    }
}

private static void Handler(object sender, ValidationEventArgs e)
{

    if (e.Severity == XmlSeverityType.Error || e.Severity == XmlSeverityType.Warning)
    {
        try
        {
            throw new Exception(
                 String.Format("Line: {0}, Position: {1} \"{2}\"",
                     e.Exception.LineNumber, e.Exception.LinePosition, e.Exception.Message));
        }
        catch (Exception ee)
        {
            Common.ErrMappingForInformix.WriteLog(ee.Message);
            ScheduleForm sf = new ScheduleForm();
            sf.ShowStatus("Error,Invalid xml file", "error", "", 1);

        }

    }

}

# Edit 1 :

XmlDocument x = new XmlDocument();
x.Load(targetFileName);

XmlReaderSettings settings = new XmlReaderSettings();
settings.CloseInput = true;
settings.ValidationEventHandler += (senderValidation, ee) =>
{
    if (ee.Severity == XmlSeverityType.Error || ee.Severity == XmlSeverityType.Warning)
    {
        try
        {
            this.validationFailed = true;
            throw new Exception(
                 String.Format("Line: {0}, Position: {1} \"{2}\"",
                     ee.Exception.LineNumber, ee.Exception.LinePosition, ee.Exception.Message));
        }
        catch (Exception ex)
        {

            Common.ErrMappingForInformix.WriteLog(ex.Message);
            this.ShowStatus("Error", "error", "", 1);
        }

    }
};

settings.ValidationType = ValidationType.Schema;
settings.Schemas.Add(null, System.Web.HttpContext.Current.Server.MapPath("~/importSchema/IntialSchema.xsd"));
settings.ValidationFlags =
     XmlSchemaValidationFlags.ReportValidationWarnings |
XmlSchemaValidationFlags.ProcessIdentityConstraints |
XmlSchemaValidationFlags.ProcessInlineSchema |
XmlSchemaValidationFlags.ProcessSchemaLocation;

using (StreamReader str_reader = new StreamReader(targetFileName))
{

    using (XmlReader validatingReader = XmlReader.Create(str_reader, settings))
    {
        while (validatingReader.Read())
        {
            //Loop through the document
            if (validationFailed)
            {
                break;
            }

        }
    }
}

It breaks the loop but it doesn't execute the event handler.

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

多情出卖 2025-01-01 19:12:32

您可以设置一个标志来指示 Handler 方法中存在错误,然后检测该标志并使用 break;(如果已设置)。

在这种情况下,最好对验证处理程序使用内联匿名委托,这样您就不需要向包含方法的类添加新的成员变量。 (如果类处理XML读取/验证,添加成员变量并不是那么糟糕)

编辑:匿名内联委托意味着您可以添加一个不必位于单独的事件处理程序中的事件处理程序方法,基本上。例如:

bool validationFailed = false; // outside of the handler
settings.ValidationEventHandler += (sender, e) =>
{
    if (e.Severity == XmlS....
    // set validationFailed = true; in here to signal failure
};

// then detect validationFailed being true to know if/when to break;

You could set a flag to indicate there's an error in the Handler method, then detect that flag and use break; if it's set.

In this case, it might be better to use an inline anonymous delegate for the validation handler, so you don't need to add a new member variable to the class containing the methods. (Adding a member variable isn't so bad if the class only deals with XML reading/validation)

Edit: anonymous inline delegate means you can add an event handler that doesn't have to be in a separate method, basically. For example:

bool validationFailed = false; // outside of the handler
settings.ValidationEventHandler += (sender, e) =>
{
    if (e.Severity == XmlS....
    // set validationFailed = true; in here to signal failure
};

// then detect validationFailed being true to know if/when to break;
江湖正好 2025-01-01 19:12:32

我只是将异常抛出到处理程序中,并在捕获它时中断控制流。但是,也要避免抛出过于通用的异常类型:更好的是使用自定义异常:

class XmlValidationFailedException : Exception {
   public XmlValidationFailedException(string message, Exception innerException) : base(message, innerException) {}

   // as per Kieren's comment, make sure this exception type is defined according to best practices
}


private static void Handler(object sender, ValidationEventArgs e)
{

    if (e.Severity == XmlSeverityType.Error || e.Severity == XmlSeverityType.Warning)
    {
        string message = String.Format("Line: {0}, Position: {1} \"{2}\"",
                     e.Exception.LineNumber, e.Exception.LinePosition, e.Exception.Message)

        throw new XmlValidationFailedException(message);
    }

然后你的循环可以变成这样:

try
{
   while (validatingReader.Read())
   {
       // do logic
   }
}
catch (XmlValidationException ex)
{
    // handle the error (log, show, ...) 
    return;
}

I would simply throw the exception in the Handler and break control flow when catching it. However, also avoid throwing too general exception types: better is to use a custom exception:

class XmlValidationFailedException : Exception {
   public XmlValidationFailedException(string message, Exception innerException) : base(message, innerException) {}

   // as per Kieren's comment, make sure this exception type is defined according to best practices
}


private static void Handler(object sender, ValidationEventArgs e)
{

    if (e.Severity == XmlSeverityType.Error || e.Severity == XmlSeverityType.Warning)
    {
        string message = String.Format("Line: {0}, Position: {1} \"{2}\"",
                     e.Exception.LineNumber, e.Exception.LinePosition, e.Exception.Message)

        throw new XmlValidationFailedException(message);
    }

Then your loop can become something like:

try
{
   while (validatingReader.Read())
   {
       // do logic
   }
}
catch (XmlValidationException ex)
{
    // handle the error (log, show, ...) 
    return;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文