简体   繁体   中英

Error handling - global error catalog?

Back when I was writing C code I might have used global #defines for error numbers. I can't do that in C#. I could use an error class, but I'd have to pass it around. Is it really such a serious faux pas to have a global error catalog class? A class containing, for example, a dictionary of errors and messages? How could it be handled better?

Ok, I could have been clearer... sorry.

Let's say I am accessing a database, or several databases, in different classes. If I get an error accessing a database I want to display an error message of some sort, but I don't necessarily want to display the system generated error message - I have my own error catalog that I want to use. Let's say I have a standard "Database Access Error" string that I want to show, but I want to add the database name and table. I could achieve that with a couple of #defines in C. How should I handle that with c# - a singleton class globally accessible that contains a dictionary? Is that a bad thing?

If you want to define a custom dictionary with code and message that will work for you, but it's not a good practice. If your code become more and more larger, giving a meaningful name to your exception is better than code. Think when there are more than one person work on the some project if you use a customclass it will be more easier as intellisense will come in help.

In c# it works in a different way you can use a custom exception class for each C code you have defined something like this

using System;

public class EmployeeListNotFoundException: Exception
{
    int _codeException; 
    public EmployeeListNotFoundException()
    {

    }

    public EmployeeListNotFoundException(string message,int codeException)
        : base(message)
    {
                  _codeException=codeException; 
    }

    public EmployeeListNotFoundException(string message, Exception inner)
        : base(message, inner)
    {

    }
   public int CodeException{get {return _codeException;} }
}

If its bad or not depends on the size of the codebase, the type of the application or program and the architecture. You could see an architecture as a set of constraints that enforces a certain 'style' to the code. If the architecture dictates that having stuff at global scope is bad then you should avoid it. If you anyway want to keep the error code information on a global scope, I would suggest wrapping your readonly dictionary in a singleton.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM