When is it appropriate to use error codes? - c#

In languages that support exception objects (Java, C#), when is it appropriate to use error codes? Is the use of error codes ever appropriate in typical enterprise applications?
Many well-known software systems employ error codes (and a corresponding error code reference). Some examples include operating systems (Windows), databases (Oracle, DB2), and middle-ware products (WebLogic, WebSphere). What benefits do error codes provide? What are the disadvantages to using error codes?

WITHIN a program one should always use exceptions instead of error codes. However, exceptions can't propagate beyond a program. Any time the error must leave the program you are left with error messages or error codes.
For simple things that will always be human-operated error messages without codes are fine. You can say "File not found" without giving it an error code. However, if it might be another computer on the other end then you should give error codes in addition. You don't want to break the other system when you change it to "File <x> not found".

I don't think I've ever used error codes in .Net except in one situation - when I was creating a console application that I knew was going to be called from another app. This other app had to know when the console app failed, and what went wrong. So, one example of when it would be appropriate would be when you know your program will be called by other programs, and you want a structured way for them to understand errors.
That said, I was a newbie to .NET at the time, and have never used error codes since.
As a side note, as a Windows guy, it's nice to be able to plop in an error code and come up with a KB article, so an error code combined with good documentation and the ability to find it = nice feelings from your users.

Very common for web service interfaces. It's very easy and standard to return a code with a description.
I agree that for most of the scenarios is old school
I'd say the biggest disadvantages it's the quality of code. You have to add more complex logic to manage error codes while exceptions are bubbled without having to use method parameters or return values.
You also have to add an "IF" to check if the returned code is SUCCESS or not, while exceptions goes directly to the error handling block.

I'm a newbie to stack overflow but...
I believe that error codes tend to be used or useful for dealing with erroneous situations that require an end-user of sorts to get involved to rectify a situation. If your code is to be maintained by another developer then exceptions is the way to go. However, in a situation where there is a problem:
in the environment that your application is running
with communication between your app and some other entity (web server, database, socket, etc)
that a device or device driver indicates (hardware failure maybe?)
then error codes may make sense. For example, if your app attempted to log into a database on behalf of your end-user, but the DB was unreachable for authentication (DB is off-line, cable is unplugged) then an error code/description combo might help the end-user rectify the problem.
Again at the developer/engineer level who will be able to touch the source code (traditional debugging and testing techniques) and modify it, use exceptions.
Hope this helps...
--jqpdev

I frequently use error codes when an error needs to be conveyed to the user, since they can be internationalized. For example, in a compiler, if there are errors in user code, errors can be signaled in the compiler backend, while the frontend can localize them into culture/language-specific strings for user consumption. Enums may be better for this purpose than raw integers, however.
I've also used them in creating an "error reporting" framework for the app. When exceptions were thrown, they were thrown with an error code, which, when the exception bubbled up, was sent (with a log) to the central server. The code helped organize the database so we could inspect logs related to a specific error.
Finally, as mentioned in a couple other answers, error codes are easy and language-agnostic to google (think Windows error codes/MS KB articles), so an error code with a description of what went wrong may be better for end-users of a technical product.
The idea of error codes is useful, but IMO they belong as exception members or as parameters to an IErrorReporter interface or something more ofthen than as method return values.

Error codes are old-school. They are of little to no value at all.
The only possible value to an error code is that it can identify a very specific circumstance. You could have a code for each point in the code base that can throw an exception. This would allow you to narrow down very precisely what the problem must be.
But nobody cares about that level of detail. Who wants to maintain such a mess. It would leave you with codes that meant something like "condition A and B but not C due to state S". It's more effort than it's worth to try to work out exactly what that means. A stack trace will be more valuable in telling you where in the program the problem occurred.
I learned to program computers before exceptions were a widespread technique. I'm so glad we got exceptions instead!

C#, and probably Java too, supports a better exception handling control flow, the finally keyword, which makes things a little nicer than using error codes. An exception object can contain any level of detail, certainly much more than an error code. So the exception object is way more practical, but you might run into an uncommon case where an error code would be more appropriate.
FWIW, C++ also supports exception objects. I don't think that C++ supports a finally keyword (though the newer C++ whatevers just might), but in C++ you also have to avoid things like returning inside a catch handler.

Error codes were designed in an age where the only way for a function to tell the caller that something went wrong was to assign a special meaning to one or more values of those which can be returned, and very frequently only a native integer or so was available for returning that special value.
For instance, in C the "get character" routine returns the next character value in ASCII, but returns a negative value if for some reason something went wrong. You are then responsible for returning to YOUR caller in a way so this error situation can be handled, and that must return etc.
The Exception mechanism is an elegant way to handle this "this is an emergency, we must return from code until something can deal with the problem". Error codes are inferior to this.

I've written many web services that are consumed by other (remote) applications. When things go badly with a request, customers more or less insist on getting a code, so that they don't have to do some horrific string comparison to find out what went wrong.
Take HTTP result codes as a fine example of this sort of behavior. "200" means happy, "300" could go either way, "400" or "500" means start freaking out.

Error codes are for if you want to send them to the user. If not, use an exception.

Sometimes you don't want to give too much information to the user when an error occurs. For example, a user is not able to sign a new contract. The error message only states something generic like "Cannot sign a new contract".
This adds difficulty to support cases where the user thinks this is not correct. If you have an error code, for example a number or an acronym, it could be part of the error message. The user wouldn't know what it means but the support staff could look it up and could then check if that specific reason for declining the new contract is indeed an error or not.

Related

How to log meaningful error messages while using P/Invoke

There are three different return/error/status code types I get while calling native function using P/Invoke.
The first one is the usual error code I get by calling Marshal.GetLastWin32Error static method.
The second one is HRESULT I get while calling some COM-helper functions.
And the third one is NTSTATUS I get while calling native apis from ntdll.dll library. I have a loging function that logs the return/error/status code as a hexidecimal number, then when an error is found in the logs I need to use google to find out what the actual error is.
So I'd like to ask if there is a good way to convert these return/error/status codes to string (preferably in English) to log the return/error/status string description instead of a number?
Is there a way to convert between LastError/HRESULT/NTSTATUS codes, so that the semantics of the error message would stay the same?
You can use errorlook tools for this purpose. This link is kind of old, I learned this in my old VC++ days and you can use it as a start point to find modern tools.
As for the logging I would suggest you keep the original error codes. Meaningful error messages are easier to read, but the original error codes are accurate keywords to the search engines.

MongoException with message ''\\0' not allowed in key

I'm getting this error while trying to log the request from C# app via PHP based API.
PHP Fatal error: Uncaught exception 'MongoException'
with message ''\\0' not allowed in key: \\0...'
After googling it for a while I came to a conclusion that I can solve it by iterating through
the array I'm trying to insert in Mongo, and replacing null terminator in keys and values.
I'm wondering is there a more elegant solution to this and how is it that Mongo cannot handle this case?
I also have mongo.allow_empty_keys set to 1 in my php.ini file.
I can't give you a more elegant PHP solution, but the reason why this is causing a problem is because BSON, and hence MongoDB uses null terminated strings, arrays etc. Hence embedding null values is going to cause confusion in general. These things will eventually get handled (see SERVER-1177 for example) but even when they are I would still recommend not using nulls in general if it can be avoided - it's too easy to imagine edge cases and possible bugs when doing so.

Useful error message for AdMembership provider

I'm looking to get usefull error message for the ADMembership provider (or our of AD at all really)
for the following cases.
User fails to log in
User fails to change password.
If the process throws an exception I use that message, and it's helpful (especially for password) but past that I'm winding up identifying a confusing reason for a generic message,then
writing specific code to detect that condition and returning a useful message.
So for example instead of a generic message "you failed the rules and complexity requirements" i can tell them WHICH rule or complexity requirement they failed, and maybe why.
I feel like this should be a solved issue and I'm reinventing the wheel, anyone out there that can point me to a better way to do this or someone who's gone down the same road and taken to the end?
Thanks,
Eric-

Is there a free alternative to Exception hunter?

I'm switching back and forth between Java and C# and one thing I miss while I'm coding in C# is the enforced exception checking (Although I admit I also find it really irritating sometimes while I'm coding in Java).
I'm aware that Exception Hunter can help you track down what exceptions a piece of code might throw but is there a free/cheaper alternative? I can't really justify £200 for this kind of software addon as it's only an annoyance rather than a major problem.
Yes. Run the free Microsoft Pex on your code. It will show all possible exceptions that can be thrown.
While I understand the enforced exceptions thing, I'm not sure how genuinely essential it is... for example, most interesting exceptions are those that you wouldn't normally include (or even expect). For example, I'm currently fighting what looks very much like a CLI bug in CF35, intermittently raising MethodMissingException from code that really does exist (emphasis: intermittently).
If you want to document your exceptions, use the ///<exception ... >...</exception> markup. For other thoughts on this theme, perhaps see Vexing Exceptions (I wonder if GhostDoc might help any?)
Get Exceptional website is one possibility. Basic idea is that you create software and all exceptions are sent to this site to your account where you can pick them up. Of course it doesn't read your code and see what exceptions are there.
I don't know if there is C# library yet but the API is not too hard.

How much information to log from errors? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
At the company I work for, I have created a Error Logging class to handle errors in my ASP.net application. It is a custom class because we are not allowed to install additional software on our servers (nLog, log4net, etc).
I currently use it in two of my projects and have seen some good results from it. Right now I am trapping the errors that cause page and application errors. It sends and stores the error message and all inner exceptions.
The problem I am having now is, I am receiving errors that I am not quite sure how to reproduce. I have not heard any error reports from any of my users. I am not sure what they are doing, or even if they are seeing these as errors.
I am thinking about creating an Event Log on each page, or the ones I want additional information on. Keeping it as a Session variable on the page, and writing events to it (start/end of functions, variable changes, etc). Then only if an error is called to have that send along with the error message to see if it gives a better picture of what is going on. I am hoping that doing it this way will not give me tons of event logs when all users access the application, just want was going on right before the error happen with the one user.
Do you know of any pitfalls I should watchout with method?
Do you have any advise for things to look for?
Update:
#Saret: I understnad where you are coming from with that response and I agree. I am fairly new to this company and still need to learn how they do things. In the past I have had conversations with my coworkers how it would be great to have this product, or use this open source project. The problem comes down to is, we work on secure systems and getting approval to get these things takes a lot of time, top cover, and dealing with all the red tape. I will look into the situation further because I believe having a good error logging system in place is important, currently nothing is being used.
#Jim Blizard: I wanted to try to get away from logging/storing everything someplace to come back and find out what is important to the situation that caused the error. I didn't want to fall into overload of information that is talked about in artical that Roberto Barros linked. My current method of thinking is, keeping a string in memory on each page, and if an error is rasied, on the pages Page_Error event, grab that string and attach it to the exception that is getting logged. That way I am only logging the error/exceptions that occured and storing the event log with that error. If nothing happens, that log that was being created is dropped into the bit bucket never to be seen again.
#Roberto Barros: Thanks for that link, I remember reading it somewhere but forgot to save it.
This might not be the exact answer you are looking for, but why develop your own error logging mechanism when there are powerful tools (which you mention) that handle all these key issues for you?
I can appreciate you are not allowed to install additional software but aren't logging libraries just classes like your custom code? Where is the fundamental difference? I would reckon the time spent worrying about implementing a logging framework might be better spent advocating and making a business case for a decent logging solution.
I once worked for an agency that would not allow installation of anything that wasn't purely my own code or their (horrid) COM objects. If you have this type of limitation, then see if you can grab the source for log4net and include in your project.
There is nothing better than log4net currently when it comes to logging.
I personally took the following approach on logging erros (and only log errors) in an asp.net application:
use
protected void Application_Error(object sender, EventArgs e)
{
Server.Transfer("~/Support/ServerErrorSupport.aspx", true);
}
(I do a Server.Transfer to preserve all post data.)
Generate an error ID which is unique for this error (so subsequent repports for the same error can be grouped). The ID is an hash calculated from a concatenated string consisting of: file, method, lineNr and error.Message. I get the file, method and lineNr values through a regex on the stacktrace.
I log all the following data to an xml structure (depending on the data type, I store the value differently, value types => ToString(), ISerializable => serialize, ...):
MachineName: Application.Server.MachineName
PhysicalRoot: Application.Server.MapPath("~/")
RequestUrl: Application.Request.Url.ToString()
ApplicationSettings: WebConfigurationManager.AppSettings
ConnectionSettings: WebConfigurationManager.ConnectionStrings
QueryString: Application.Request.QueryString
FormPost: Application.Request.Form
Session: Application.Session
HttpHeaders: Application.Request.Headers
Save the xml structure as a local file containing the error ID and a timestamp.
I chose this approach because:
I can mail the rapport (xml-file) to myself (during test/debugging very easy)
store it locally or in a database during production
because the file is just a (dump to hd) save not much can go wrong during the creation of the error report (like a server connection, db problems, etc), just make sure you have write permissions.
Additionally on the servererrorsupport.aspx page, after saving the xml file, the user gets the option to include extra information and to add an emailaddress to keep updated on progress regarding the bug. This gets appended to the xml document.
I use an xslt file to format the error data (xml) in a nice error report.
For errors, I'm a big fan of logging A LOT. When things go wrong information is very valuable. I would keep the entire log in one place (text file or database table) with a session identifier to group relevant events together.
Here's what I like to log:
error/debug level (info, debug, problem, crash, etc...)
time
descriptive text (usually one line)
stack trace (if possible)
data (user, session, variable values, etc...)
The simplest way is to write to a text file, but it can be nice to have it in a database. You can also use the Windows event log. Some things to watch out for. Hmm... You'll need to clear out your logs periodically.
Funny story: one time we had an error logger that logged to the database, but we had bad database credentials which caused an error which was then logged... Ended up getting stack overflows from the recursion (IIRC).

Categories

Resources