Handling (possibly-changing) error codes of a library using exceptions - c#

Let's say you are using a library that returns error codes. You'd like to write a wrapper for the library, and you'd like to handle errors with exceptions in the code.
If the library is still in development by someone else, and if the error codes may change (there can be new ones, there can be deprecated ones, or some error codes may change meaning slightly), what would your solution be to handle this?
This is the situation that I'm in right now. In my case, the library is written in C++, and we're using C#. The coder of the library says the error codes may change, and I have to find a way to work with it.
Our initial solution is to:
Create an XML file that has the error codes in different categories (terminal ones, input errors, and so on).
Wrapper fetches these error codes on start.
Throws the appropriate exception by checking the category of the error code.
So let's say a method returns error code 100, then the wrapper checks the category of the error code. If it is a terminal error it throws a terminal error exception, if it is a user input error it throws a user input error exception.
This should work, but I feel like this is not the optimal solution. I'd like to know how good written enterprise software handle change of error codes.
What would you suggest doing?
Edit: I have already questioned the fact that error codes will be changing and the coder of the library says the code is in development. It's an algorithm, so even the way the algorithm works changes as it's original research (he's writing his PhD on that). So he says there may be different errors, or some may be irrelevant in the future.

The data-driven approach you're taking, using the XML file, seems like a good one, given the circumstances. However I'd question why the error codes are changing at all - this suggests that no proper design has been carried out for the library being developed. It ought to have a well-defined structure for its error codes, rather than requiring you to keep changing your interpretation of them.
You may want to try having an overall "library exception" exception class, and subclassing it for each different type of exception you want to throw based on the "type" of the library error. At least that way, you can catch all library errors, even if one of the specific types of exception slips through the net. ie. you'd catch something like LibraryException after trying to catch TerminalErrorException.

I guess you will solve this problem easier if you change your vision of the situation a little bit:
You are dealing with the framework, let's call that an external
framework.
On the other hand, you are writing a wrapper for the
framework - internal framework.
Your code (client application) uses internal framework, assuming that it provides the functionality used for the problem domain. As I understand, and as I believe, client application should not have any idea about the external framework.
Now, the question comes down to the following one: is the internal framework's functionality clearly outlined and finalized? or is that changing too?
If it's changing (possibly because of the external framework), then the internal framework is under the development. This means, client application needs to wait until internal framework is ready to announce a first version ready (possibly after the external framework is complete).
Now error handling:
Errors in the application serve like contracts. Caller of the function expects particular exceptional situations, and particular kinds of errors only. Each possible error is predefined and documented by each function, similar to its input parameters and return values.
What it means for you:
Define the final design of the internal framework (the sooner the better).
Decide what kinds of errors each function of the internal framework can throw.
Use internal framework from your client application and expect only expected and documented exceptions. Don't try/catch anything that is not expected from the internal framework. Basically, follow the contract.
If error code changes, that does not change the concept of the function in the internal framework. It still needs to throw the same kind of error it threw before (according to the contract). The only part that needs to be changed is, how to translate the new code to one of the expected (contracted) errors. You can solve it any way that works better.
Why is the last assumption fine? because we said the internal application's design is final and is not going to change. Error contracts are part of the final design too.
Example:
//external.
int Say(char* message);
//internal.
///<summary>
/// can throw (CONTRACT): WrongMessageException, SessionTimeOutException
void Say(string message) {
int errorCode = External.Say(message);
//translate error code to either WrongMessageException or to SessionTimeOutException.
}
Cannot translate? something is wrong either with current contracted errors or the external framework: maybe you should terminate the process? something went wrong, unexpected!!!
//client.
...
try {
Internal.Say("Hello");
}
catch (WrongMessageException wme) {
//deal with wrong message situation.
}
catch (SessionTimeOutException stoe) {
//deal with session timeout situation.
}
Let me know if anything raises the question.
Translating error codes to Exceptions:
This obviously is some kind of categorizing for each error code. Category can be each destination exception, and exceptions can be categorized by functions. This is exactly what the error contract means: categorize Exceptions by functions; and categorize error codes by exceptions.
Below is a pseudo configuration for this. Take this as an initial idea of how to categorize:
category Say [can throw]: { WrongMessageException, SessionTimeOutException }
category WrongMessageException [by error code]: { 100, 101 }
category SessionTimeOutException [by error code]: { 102, 103, 104 }
Of course you don't need to write a parser for such kind of impressions (this was human readable pseudo configuration). You can store similar sentences using XML or any kind of source, which will help you configure error translation rules and function contracts.
Reference
Book: Jeffrey Richter - CLR via C#, 3rd edition. Chapter 20 - Exceptions and State Management. Sub-Chapter - Guidelines and Best Practices. Sub-Sub-Chapter - Hiding an Implementation Detail to Maintain a "Contract".
This chapter will describe exceptions as contracts and will explain how to categorize contracts thrown by the function. This can confirm the correctness and the credibility of the explanations provided here.

What about this:
You said you have stored Error categories some where (DB or XML file)
lets amuse we have some master detail tables called ErrorCategory(Master) and ErrorDetail(Detail)
I will recommand adding a column (property) to your Errorcategory Table
Called CustomExceptionType, it will be a text property containing full name of assembly and class name of specified exception (ex: CustomExceptions,CustomExceptions.TerminalError )
We will need a base class 4 all of our custom exceptions, lets call it BaseCustomException calss
We will need an ExceptionFactory Class lets call it CustomExceptionFactory class
Our ExceptionFactory will have a method called CreateException, something like this
Public BaseCustomException CreateException(EceptinCategory category, ExceptionDetail detail)
{
var customException = Activator.CreateInstance(category.CustomExceptionType) as BaseCustomException;
customException.SetDetails(detail);
return customException;
}
so in run time our CustomExceptionFactory object will use CustomExceptionType to create a an instance of specific exception using Reflection.
I prefer CustomExceptionFactory & BaseCustomException to be implemented in a assembley
and all derived CustomExceptions be implemented in another assembly so our main application will be non related to CustomExceptions.Dll
In futur by changing of C++ factory, our main application will not need rebuilding and all we need is change in data of tables and impementaion in CustomExceptions.Dll.
(same solution could be implemnted using XML or Configuration file or ...)
Hop this will help.

OK, if you want to be flexible and not to depend on the code I think using reflection to generate custom class when you first run the application would be the best. Here is the rough explanation. If you like it I can explain it further.
The provider of the C++ code should create a class that will hold all error codes - for example public class Errors{public static readonly IOError = 100}.
When you start your application you will check this class for modification and if it is modified you will generate exception class for each error code.
In the above example it you will generate class IoException that inherit Exception .net class.
After that you can use it in the wrapper and catch each exception individually.
Another possible solution is to amend the xml that you are mentioned - for each error code add exception class - using the example the for error code 100 you will have IoException class. after that you need to implement this class and use it...

Better to depreciate old codes and leave their designations reserved than to have your code designations constantly changing. Since your author doesn't seem interested in design, have him report warnings and errors on the stderr stream that you can retrieve.
In addition, it seems simple enough to construct a CSV or XML with code-string pairs that the algorithm writer is free to edit as he sees fit. Reserve certain ranges of code number for different types of errors (1000s for input errors, 2000s for terminal errors, etc) have your wrapper interpret the return code using the code-string pair he wrote.
Then throw your exception based on the type of error, determined by the number range.

Related

Contract.Ensures and Exception Handling

I recently discovered the .NET Contracts API, and, although I don't like the way of implementation using methods and not an extended syntax (Sing# did it right, in my opinion), I prefer using them over the old / regular way using if's for e.g. null-checking.
I'm also approaching my first Contract.Ensures-calls and I stumbled over the question how we would deal with Exceptions in a method containing a Contract.Ensures that suffered from an exception while running?
The word Contract.Ensures kinda feels like I have to handle the exceptions inside the method and get my class into correct state again, but what if I couldn't?
Let's say we have this class here:
public class PluginManager
{
private ILoadedFromAtCompileTimeUnknownAssembly extension;
public bool IsFinished { get; private set; }
public void Finish()
{
extension.Finish();
this.IsFinished = true;
}
}
can we use Contract.Ensures to ensure IsFinished is true after the method completed?
Yes. Ensures basically means "Ensures if the method terminates normally", i.e. without exceptions.
I find it very hard to get the concept of code contracts right. Code Contracts are meant to find programming errors. If applied that way you can remove the contracts of your release build and your application will continue to work perfectly.
BUT it is very hard to distinguish programming (aka logic errors) from configuration and input data issues. These checks must remain in your release builds. It is therefore a bad idea to use Code Contracts to check if an extension/plugin did correctly load because it is usually configured into your application. If you remove the contracts in your release build you get differerent behaviour of your application depending if you configure your app wrong in debug or release builds.
Contract violations are reported with only one exception type which makes it impossible to react in upper layers of your application to e.g. a configuration issue or a logic bug in your application. With react I do not mean to continue but to present a remotely useful message to the user/developer what went wrong.
Code Contract do look nice at the surface but I fear that most people use it in the wrong way. It is not meant to replace all of your null checks for input validation in your methods. You should replace only from the methods the null checks with code contracts where your are sure that a logic problem an not the input data is the root cause.
If you expect a file name in your e.g. console application as input and the the user did forget to supply the file name at the command line it is not a good idea to the greet the user with a ContracException.
The error message would be confusing to the user.
You cannot differentate programming errors from user input validation issues.
You cannot catch any specific ContractException because the exception type is internal.
See user documentation.
7.6 ContractException The ContractException type is not a public type and is emitted as a nested private type into each assembly for which
runtime contract checking is enabled. It is thus not possible to write
catch handlers catching only ContractException . Contract exceptions
can thus only be handled as part of a general exception backstop. The
rationale for this design is that programs should not contain control
logic that depends on contract failures, just like programs should not
catch ArgumentNullException or similar validation exceptions.

How is compiler dealing with these Generic Plugin Interface instance methods?

I'm working with some, unfortunately largely undocumented, existing code and I'm having trouble understanding how it calls upon the methods of the plugins it loads.
My aim at the moment is simply to step into one of the methods loaded via the plugin manager, as it's causing an exception. However I had to rebuild the pluginManager from the source to get debug symbols and when I reference this new DLL version the compiler throws up arms.
The code appears to load the plugin into plug.Instance and then access the specific methods like so plug.Instance.ReturnLeaNumber();
This compiler error makes sense, because it doesn't know the details of the plugins. What confuses me is how the compiler ever knew these where valid before run time, when no plugins are initialized. I can step through the code that doesn't work now with the older DLL!
This is an example of where the program loads up a plugin.
plug = GenericServicePlugins.AvailablePlugins.Find(Application.StartupPath + "\\Dlls\\SchoolInterface.dll");
// Compiler doesn't like this next line anymore though
plug.Instance.Initialize(null, null);
If there are any differences between my rebuilt library and the previously working one, I can't tell how as the versions match up with the ones in our source control. Would appreciate some advice on where to start looking!
public interface IGenericPluginMasterInterface
{
String returnName();
void Initialize(ExceptionStringResources.Translate ExceptionStrings);
Object ExecuteFunction(String macAddress, bool log, String functionName, LoginCredentials logonCredentials, WebConfiguration webConfig,
Int64 dataLinkId, DataLinkParam[] dataLinkParams, String dataName,
DataParam[] dataParams, Object[] additionalParams);
}
Rest of Manager code on PasteBin
How does the compiler know about these plug.Instance.Method() methods before runtime?
Edit:
I've not quite worked this out yet, but there was a "PluginsService" file I missed which partly mirrors the "GenericPluginServices".
I think this error could have been caused when I removed parts of this class that related to an now defunct plugin, which I am looking into. However I figured posting this other code snippet would help the question.
PluginService.cs code
GenericPluginService code
Find returns AvailablePlugin, so .Instance is of type IGenericPluginMasterInterface; if so, indeed; that .Instance.ReturnLeaNumber() can't possibly work...
The only way that could work (without introducing some generics etc) is if .Instance actually returned dynamic. With dynamic the name/method resolution is happening at runtime. The compiler treats dynamic very deliberately such as to defer all resolution to runtime, based on either reflection (for simple cases) or IDynamicMetaObjectProvider (for more sohpisticated cases).
However, if the code you have doesn't match what was compiled, then: we can't tell you what it was. IMO, the best option is to get hold of the working dll, and look at it in reflector to see what it is actually doing, and how it is different to the source code that you have.
Actually, strictly speaking it could still do that with the code you've pasted, but only if plug is typed as dynamic, i.e. dynamic plug = ...

designing exceptions for custom dll used by third party web sites

I'm designing a class library that will be sent out to the public for use with their applications. It interacts with a custom db system that they need to install on their servers.
I'm having trouble deciding how to throw exceptions from this dll which is mainly a wrapper to the custom db system.
I assume I have to create custom exceptions that can indicate various types of errors, including validations, data integrity errors etc.
This dll will be eventually used by public facing web sites. I would like to provide a good feedback to the end user by throwing proper exceptions so that the site can make a decision to display them or not. But I'm not sure if it is possible to anticipate all the user input errors. In case of an unexcepted event, do I just throw a regular .net exception with the error message?
I have used many third party dlls that do not give you a clear way to handle the errors and I don't want to be one of them.
The only reason to creaqte a custom exception is if the calling code needs to catch it explicitly to know the difference between your exception and some other exception.
If the caller is going to treat your exception exactly the same as, say, InvalidOperationException, then you should throw InvalidOperationException instead.
See Choosing the Right Type of Exception to Throw.
You should rethrow custom exceptions where your DLL knows more about the error than is indicated in the exception you are catching, if you don't know about it, then you don't know MORE about it, just pass it along.
Just to be clear, this doesn't mean you can't throw your own exceptions on detecting errors.

Best practices when reporting exception messages to the user

In my ASP.NET MVC application, I do not want to report all exception messages to the user. But there are certain types of exceptions that I'd like to report to the user, so I created an action filter to decide if it's this particular type of exception, and if so then display the exception's message, otherwise display a generic message. So I created a custom exception called ClientException.
My filter looks something like this:
if (filterContext.Exception is ClientException)
message = filterContext.Exception.Message.Replace("\r", " ").Replace("\n", " ");
else
message = "An error occured while attemting to perform the last action. Sorry for the inconvenience.";
filterContext.HttpContext.Response.Status = "500 " + message;
I read this http://blogs.msdn.com/b/kcwalina/archive/2007/01/30/exceptionhierarchies.aspx where the author recommends using existing .NET exception types to report usage errors. However, by introducing my custom exception, I just have to do a single check in my filter. Is my approach okay?
I like this approach for a couple of reasons.
First, it fails safely. If someone doesn't explicity throw a ClientException, then the exception details are not reported. Forgetting to display something is a lesser problem than accidently displaying something.
Secondly, it allows the decision about whether to display the exception to be made at the proper place. Not all IOExceptions are displayed, for example. Some may be, and others wont be. The specific exceptions can be caught and transformed anywhere in the call stack, so that tranformation can be made at a place where it is known to be correct.
Both of those things together mean that a future developer will not innappropriately change a whole class of exception to be displayed, or think that something won't be displayed when it actually will be.
Also, the purpose of the using a particular exception type is to determine later what action to take in response to that exception. "Display this message to the user" is a perfectly good action to specify. Once that decision has been made, then the exact nature of the exception is completely irrelivant. (The original problem may be put in the InnerException property, for logging purposes, of course.)
So, in my opinion, this is a good design.
Your approach is fine IMO but there are alternatives. (We're software developers so there are always alternatives.)
You could harness the Exception Data dictionary to store a flag indicating whether or not an exception is a client exception. Then you could have your filter check for the existence of the flag.
If your approach works for you then it is fine. And are you surprised that a Microsoft blog is recommending that you use their Exception class? ;)
There are some .NET library features and 3rd party OSS stuff that will only work with .NET exceptions however.
To get the best of both worlds you could always extend the .NET Exception object into your own.
I would use different Threshold values based on the type of exceptions, and these Threshold values would be associated with the exception messages.
Based on the particular Threshold value logic you may want to decide whether or not to show exception.
My concerns with this solution is that very likely these exceptions will typically be thrown by objects in a business layer (or model objects in MVC terminology). The usage you describe is really what I would consider to be a presentation concern.
Typically you'd need to rethrow whatever exception you have in your model, only to communicate whether or not the exception can be exposed to the user or not.
What do you expect the user to do with the information? If the user can fix the situation perhaps there should not be an exception to signal the state to begin with?
I would stick to catching specific exceptions per case and do presentation decisions at the spot. You may send out an exception, as caught, used as model to a view though. I would still let the controller decide, not whomever throws the exception.

Is passive logging possible in .NET?

I'm frequently frustrated by the amount of logging I have to include in my code and it leads me to wonder if there's a better way of doing things.
I don't know if this has been done or if someone has come up with a better idea but I was wondering is there a way anyone knows of to "inject" a logger into an application such that it passively monitors the thread and quietly logs processes as they occur without having to do things like:
public void MyProcess(int a, string b, object c)
{
log(
String.Format(
"Entering process MyProcess with arguments: [a] = [{0}]; [b] = [{1}]; [c] = [{2}]",
a.ToString(),
b,
c.ToString()
);
try
{
int d = DoStuff(a)
log(
String.Format(
"DoStuff({0}) returned value {1}",
a.ToString(),
d.ToString()
)
);
}
catch (Exception ex)
{
log(
String.Format("An exception occurred during process DoStuff({0})\nException:\n{1}",
a.ToString(),
ex.ToString())
)
}
}
What would be great is if I could say to my logger:
Monitor(MyClass.MyMethod)
It would then monitor everything that goes on inside of that method including passed in arguments along with method calls and values passed into those methods, exceptions that occur etc.
Has anyone implemented something like this in the past? Could it even be implemented? Is logging in this fashion just a pipe dream?
I'd love to design something that would do this, but I just don't even know where I'd begin. Of course, I don't want to reinvent the wheel either, if it's already been done, it would be great if someone could point me in the right direction.
Any suggestions would be gratefully received...
Edit: I thought I'd comment on an answer which queried as to the level of detail required in the log. It is frequently required that configurable levels of logging be provided such that if the configuration specifies detailed logging then everything is logged, whereas if critical logging is configured then only certain information is logged along with exceptions. If fatal logging is configured then only information which causes the application to die would be logged. Would something like this be configurable or would AOP require 3 or 4 different builds depending on the number of logging levels?
I frequently use 4 levels: Fatal, Critical, Information, Detailed
You can use PostSharp to log "around" the method. This is exactly the kind of thing AOP is good at. You might want to start with Log4PostSharp - a plugin specifically for logging.
This is the classic example from Aspect Oriented Programming. See PostSharp for a very good CLR-based library.
This is one of the textbook (not sure which textbook has AoP in it but you get the idea) examples of AoP - logging : where you want to stick something before and after a method.
You might want to explore the AoP route, PostSharp is one of the popular ones, along with Microsoft Unity (IoC too), Castle.
One simplistic example of AoP is you add your code before and after methods, instead of adding the method calls inside the actual methods. As you've tagged the question with C# you might want to just look into making an extension method to log it, which is already in this question.
I would take a practical approach: how much actual logging are you doing? Can you get away with just an extension method instead of razzle-dazzle'ing the person reading your code. The logging built into the .NET framework is decent already.
In addition to the logging methods mentioned by Jon, its probably also worth noting another useful feature in VS for tracing program flow, and that is the ability to have non-breaking breakpoints that will simply output a message or run a macro when hit (note you can print variable values as well)
Right click on your breakpoint and choose the When Hit... context menu item.
And of course one other very useful feature is the Trace object and Trace Listners in System.Diagnostics.
I've written a logging library recently that uses the IDisposable interface to wrap regions with logging context. Basically, there's a LogSite disposable object that you use like this:
using(var logger = new LogSite("methodName", new object[] { p1, p2, p3 })
{
// code that does stuff goes here
}
The LogSite object has a bunch of convenient overloads for the constructor such as MethodBase so you can just use MethodBase.GetCurrentMethod() and use reflection to get the actual name of the method and parameters (instead of a hard-coded strings).
The way it works is this -- In the constructor, it writes to the log with all the trace information to indicate it entered the block. In the Dispose method, it writes an exit entry.
While disposing, it also checks Marshal.GetExceptionCode() for a non-zero value to see if the code inside the using threw an exception or exited normally. It doesn't give you the exception, so that will have to be logged explicitly in the catch handler, but it does indicate "pass/fail" for that region. This allows your logging scope to be more specific than just the method, since you could have lots of these blocks in a single method, and know which one threw the exception exactly.
Also, since there's a "logger" object now available, your catch handler just looks like:
try { ... }
catch (Exception ex)
{
logger.LogException(ex);
}
The logger already knows the method name, parameter information, and all that, and has internal methods for formating the exception information.
Getting into the architecture below this high-level object, there's a concept of "LogDisposition" which handles the "pass/fail" we determined earlier, and there's a concept of "LogEntryType" which is a filter (implemented with Flags enum) that indicates what kind of log entry is being passed (Error, Trace, etc).
The thing that actually does the logging is just a publisher/listener pattern. The publisher takes the passed in log entry, and much like a multi-cast delegate, keeps a registry of LogListener instances (should be setup at the start of program, or added in dynamically as needed), and passes the log entry to those instances.
The LogListeners in turn, filter out what kind of log entries they care about.. So if you don't want the method entry and exit points for non-error conditions, they don't have to show up in the log. This can be controlled at run-time to allow the user to do things like turn on and off detailed logging at will. Since the publisher can write to a variety of loglisteners, you can hook up something that writes to a file, or writes to the database, or displays error notifications in the GUI... etc.
It's a pretty good system, and requires a relatively small amount of coding to get relatively rich logging.
I could give you a code sample if you wanted... You can contact me through my (nearly completely inactive) blog (see my account profile).
Hope that helps.
I use the opensource Apache log4net in all of my projects. It's a very simple implementation with all kinds of extensions that allow you to log to databases, zip files, rolling log files, RRS feeds, telnet clients, etc. Logging is basically as simple as:
'Will print stack trace after message'
log.err(ex.message,ex)
log.warn("warn")
log.info("info")
log.debug("debug")
Logging parameters such as the output format and log level to output are all read real time while your app is in runtime.

Categories