I'm writing a small library to open an xml. If reading top level xml element fails, the library throws an exception.

However, if reading one of the minor, lower level xml elemetns fail, I currently throw the exception to stop the constructor, but then catch it and do nothing with it, since the error may not be critical.

I need a way to tell the main program that something did happen.

I can think of two ways of making that happen. One is to store offending data into some structure and make it accessible to the program which calls the library. This is my first choice, bit I'm open to suggestion.

Another is to pass some kind of stream to which the library will write errors to.

The problem here is that I either have to pick between library not being dependent in the stream I pass and making sure that error output style matches the one of the main program.

Is there some OO way this is normally done? Is there a better way?

EDIT: I'm not writing an xml reader, I'm using the one that comes with .NET. The data I get from XML may or may not be okay for my use, that is the bit that I'm dealing with.

有帮助吗?

解决方案

It sounds like you need to use a delegate to solve this. By passing a method to the library, it can call that method when an error is thrown. In the main application, a user would simply need to write the specific logging code that would conform to whatever standard they have set in their own application, and also any other actions that should occur as a result of the error being caught.

其他提示

There are virtually dozens of correct ways to handle this problem, and none of them is "better" or "more OO" in general. You just have to decide which way fits better to your overall requirements, what kind of information you can and want to return in case of a "non-critical" error.

  • Using a special data structure or return value, as suggested by yourself, is probably the most simple approach here and often sufficient for many cases.

  • Using a delegate, as suggested by Kevin Mills, has benefits if you want to get the error information immediately when it is encountered, and log immediately, in case you expect the whole parsing process to stop at a later time, maybe because of an exception.

  • In case there is some non-critical element missing, another approach might be to provide sensible default values for such missing elements and do not signal any warning to the caller at all. But beware, make sure you use this tactics only if there is no chance to hide some error by doing so.

And yes, it is also a good idea not to log warnings directly into some stream, for example, if you want to keep the lib as general as possible, with no local dependencies (like the expectation of an english-speaking user).

许可以下: CC-BY-SA归因
scroll top