Question

I have a process that is parsing an XML file.

This is occuring in the PAckage Class.

The Package class has a Delegate that sets the object to an invalid state and captures the detailed info on error that occured the Package Class

For simplicity I am showing the filitem being passed to the package..

i.e `

foreach( var package in Packages)
{
try
{

    package.ProcessXml(fileitem.nextfile);

}
catch (CustomeErrorException ex)
{
    Logger.LogError(ex)
}
}

Inside The Package my validations look something like this

var Album = xml.Descendants()
    .Select(albumShards => new Album {
      Label = (string)albumShards.Descendants(TempAlbum.LabelLoc).FirstOrDefault() == "" ?
FailPackage("Error on label Load",Componets.Package,SubComp.BuildAlbum ) :  (string)albumShards.Descendants(TempAlbum.LabelLoc).FirstOrDefault()

On this validation I check to see if "" is returned for label... if so Call Failpackage with error info and create exception

 protected override void FailPackage(string msg, LogItem logItem)
         {
             Valid = ProcessState.Bad;
             Logger.LogError(msg,logItem);
             throw CustomErrorException(msg, Logitem);

         }

that is captured via the containing try catch block

My concern is that I am using Exceptions for Program flow ... how else should I look at approaching this problem or is this a valid Pattern.

Was it helpful?

Solution

ProcessXml fails to do what its name implies in certain cases; these are error cases. Exceptions are for error handling, despite what the name implies.

One of the biggest misconceptions about exceptions is that they are for “exceptional conditions.” The reality is that they are for communicating error conditions.

Krzysztof Cwalina, Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries

In other words, you're in the right. :)

Read the chapter on exceptions in the above book for some excellent guidelines.

OTHER TIPS

You can put the error along with the ProcessState:

foreach( var package in Packages)
{
    package.ProcessXml(fileitem.nextfile);
    if(!package.Valid)
        Logger.LogError(package.Error)
}



var albumShards = xml.Descendants().FirstOrDefault();
if((string)albumShards.Descendants(TempAlbum.LabelLoc).FirstOrDefault() == "")
    return FailPackage("Error on label Load",Componets.Package,SubComp.BuildAlbum );

album = (string)albumShards.Descendants(TempAlbum.LabelLoc);


 protected override void FailPackage(string msg, LogItem logItem)
 {
     Valid = ProcessState.Bad;
     Logger.LogError(msg,logItem);
     Error = msg;
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top