Is the following method of exception handling correct? I am finding it difficult to log the error and finally send the log file through email. Where do I write code to log the error and send email?
A major problem I get is that when the exception is generated in SomeClass1
it is logged two times - the second time from SomeClass2
. Is it a good idea to create a single custom exception type (SomeException
in the example) and wrap the System.Exception
whenever it occurs?
Also I am confused about how and when to show error message to the end user when we have a chain of try-catches calling one another.
class SomeClass1
{
public static DataExtract(string sourcepath)
{
try
{
OleDbConnection oledb = new OleDbConnection();
oledb.ConnectionString = "someconnectionstring";
CompanyOLEDB.Open();
}
catch (Exception e)
{
throw new CustomException(e);
}
}
}
class SomeClass2
{
private void SomeMethod()
{
try
{
// some code
// some code
SomeClass1.DataExtract()
}
catch (Exception e)
{
throw new CustomException(e);
}
}
}
public class CustomException : Exception
{
protected CustomException() { }
public CustomException(Exception e)
{
Log(e);
}
public CustomException(ExceptionType type)
{
this.Data.Add("Type", type);
this.Data.Add("Message", "No message specified");
}
public CustomException(ExceptionType type, string message)
{
this.Data.Add("Type", type);
this.Data.Add("Message", message);
}
public static void Log(Exception e)
{
System.IO.File.WriteAllText(Logfile.txt", e.ToString());
}
public static void Sendmail()
{
ExceptionMail.Sendmail();
}
}