11

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:

  1. Create an XML file that has the error codes in different categories (terminal ones, input errors, and so on).
  2. Wrapper fetches these error codes on start.
  3. 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.

hattenn
  • 4,371
  • 9
  • 41
  • 80
  • You could have the C++ API provide an export to read exception details from a code, then build a generic exception, a bit like COMException (it also has an HResult property that represent the error code). – Simon Mourier Feb 02 '13 at 11:29
  • But building a generic exception won't be useful. I need specific exceptions. If I want to build one general exception, I can easily check if the returned error code is equal to zero or not. If it's not I can throw the general exception. – hattenn Feb 06 '13 at 09:59
  • 1
    Why do you need specific exceptions? You can have one unique exception type with custom properties, for example the associated error code to that exception. – Simon Mourier Feb 06 '13 at 10:06
  • Because I want to handle different exception types differently. For example I want to terminate when it's "out of memory exception", and I want to terminate when it's "argument is invalid exception". If I only have one exception class, then after catching it I need to check the error code, and conditionally do different things. Which in turn will make the code harder to maintain. – hattenn Feb 06 '13 at 10:13
  • Well, this is how COMException works. Defining specific exceptions is ok when you have only a few (and in this case, there is no real sense in the whole question). If your library reports hundreds of exceptions, catching them specifically will sure be hardest to maintain and less practical than use conditional code. – Simon Mourier Feb 06 '13 at 11:26
  • Is it possible that you agree that for new error code the authors will use ranges e.g. - 0 to 10000 - existing error codes, - 10000 to 20000 application errors or what you call terminal errors, - -1 to -10000 user input errors, - etc? – tymtam Feb 05 '13 at 00:15
  • Unfortunately he says the error codes depict what part of the dll the error is from, so they may be changed. But that's not the case. Let's say we use this, separate error codes to three different exception types. Then if I want to introduce a fourth exception class, I'm back in square one. – hattenn Feb 06 '13 at 09:53
  • I don't agree with that. With conditional version, I have to handle error codes in compile time in my code. So when a new error code is added, chances are I will have to change the code and recompile. With an XML file, at least the error codes will be fetched during run time and won't require a recompile. – hattenn Feb 06 '13 at 17:28
  • By the way, there are quite a lot of error codes, but there will only be a couple exception classes. Many of the error codes don't need to be handled differently so I won't be implementing exception classes for them. – hattenn Feb 06 '13 at 17:36

5 Answers5

5

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.

Jez
  • 27,951
  • 32
  • 136
  • 233
  • I have already questioned it and he 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. – hattenn Jan 31 '13 at 11:19
3

I guess you will solve this problem easier if you change your vision of the situation a little bit:

  1. You are dealing with the framework, let's call that an external framework.
  2. On the other hand, you are writing a wrapper for the framework - internal framework.
  3. 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:

  1. Define the final design of the internal framework (the sooner the better).
  2. Decide what kinds of errors each function of the internal framework can throw.
  3. 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.
  4. 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.

Tengiz
  • 8,011
  • 30
  • 39
  • Thanks for the answer. The important part is translating the error code to a pre-defined exception. As I said, what we planned to use was to have a database of error categories and the error codes they contain. I haven't seen a better way suggested so far. – hattenn Feb 08 '13 at 17:29
  • By answering, I tried to say that the source where you store the mapping does not really matter. Codes change often? - store in the configuration file. No? - you can even hardcode. I saw you complained that codes change. That's very normal in the ongoing projects. So, if you want to minimize your code change efforts, simply store them somewhere. But at the end wrapper function should translate any change to the predefined exception types. – Tengiz Feb 08 '13 at 17:46
  • @hattenn, I re-read your comment and added few words to my answer (Translating error codes to Exceptions). The main idea remains unchanged. This just confirms what perhaps you've already figured out. – Tengiz Feb 08 '13 at 20:32
  • thanks. As you said, it confirms what I have already thought. I appreciate the second-opinion though. – hattenn Feb 08 '13 at 22:08
  • Honestly, doesn't add much to what I have just said, just confirms it without citing any credible source or previous experience. But I don't want the bounty to go to waste and Tengiz has put a lot of effort in writing the answer, so the bounty goes to him. – hattenn Feb 09 '13 at 12:09
  • @hattenn, even though the bounty is already taken (thanks for that!), I have added the reference to the rather credible source, which can add something to my answer. – Tengiz Feb 09 '13 at 16:23
1

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.

Mohsen Heydari
  • 7,256
  • 4
  • 31
  • 46
  • Unfortunately creating different exception classes for every error code is not that useful, IMO. If two exception classes will be handled in the same way, then probably you're better off having only one exception class for both. – hattenn Feb 08 '13 at 22:03
  • I mean having separate exception class per Category not for every Error code. also you can have a single custom exception implementation 4 many Error codes. – Mohsen Heydari Feb 08 '13 at 22:18
0

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...

Radin Gospodinov
  • 2,313
  • 13
  • 14
  • I think in concept, it's not much different than the XML one, at the same time it sounds like unnecessary amount of work for such a thing. And even though I may have an exception class for all the error codes (which is not necessarily a good thing), I will only be catching the base exception classes, which in the end will not add much of a value. – hattenn Feb 06 '13 at 09:56
  • That is true. But you can easily change the proposed approach to something that fits to your needs. You can create one exception class that will contain an Enum(or just the error code). – Radin Gospodinov Feb 06 '13 at 10:15
  • Well having one exception class is easy. But then, when I want to handle exceptions differently I have to do it in a conditional way (if error code was x do this, if error code was y do that). Which kind of defies the point of exceptions, IMO. – hattenn Feb 06 '13 at 10:27
0

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.

Phlucious
  • 3,704
  • 28
  • 61