I have made some user-defined exceptions and I would like to add an error level to each exception. forexample userInputerror, and internalError. The reason I'm coding this, is because I want to learn about exceptions so that's why I am reinventing the wheel instead of using log4net.
My code looks like this.
I have a class called MyException:
namespace ExceptionHandling
{
public class MyException : ApplicationException
{
public MyException(string message)
: base(message)
{
}
public MyException(string message, Exception innerException)
: base(message, innerException)
{
}
}
}
One of my exceptions is an IntParseException, this class looks like this:
namespace ExceptionTester
{
class IntParseException : MyException
{
string dataToParse;
public IntParseException(string dataToParse)
: base(" [ERROR] Could not parse " + dataToParse + " to int")
{
this.dataToParse = dataToParse;
}
public IntParseException(string dataToParse, Exception innerexception)
: base(" [ERROR] Could not parse " + dataToParse + " to int", innerexception)
{
this.dataToParse = dataToParse;
}
}
}
In my mainform, I am handling my exception like this:
private void btnSave_Click(object sender, EventArgs e)
{
try
{
try
{
int.Parse(txtNumber.Text);
}
catch (Exception ex)
{
throw new IntParseException(txtNumber.Text, ex);
}
}
catch (Exception ex)
{
LogWriter lw = new LogWriter(ex.Source, ex.TargetSite.ToString(), ex.Message);
logwindow.upDateLogWindow();
MessageBox.Show("Please enter a number");
}
}
I'm logging my exceptions and that class looks liked this:
namespace ExceptionTester
{
class LogWriter
{
public LogWriter(string exSource, string exTargetSite, string exMessage)
{
StreamWriter SW;
SW = File.AppendText(@"logfile.txt");
string timeStamp = "[" + DateTime.Now + "] ";
string source = "An error occured in the application ";
string targetSite = ", while executing the method: ";
SW.WriteLine(timeStamp + source + exSource + targetSite +exTargetSite + exMessage);
SW.Flush();
SW.Close();
}
}
}
So my question is, how do I add an enum type to my exceptions which would make it possible for me to chose which kinds of exceptions I want to log. forexample, at somepoint I would like to log all exceptions but at another time I only want to log userInputErrors.
I suggest creating a new base exception class inheriting from Application Exception, which include the enum:s
Derive all your exception from this base class, and assign the level as needed - maybe in the constructors, or using a parameter passed from the app.