ユーザー定義の例外を作成しましたが、各例外にエラー レベルを追加したいと考えています。たとえば、userInputerror、および internalError です。これをコーディングしている理由は、例外について学びたいからです。そのため、log4net を使用する代わりに車輪を再発明しています。
私のコードは次のようになります。
MyException というクラスがあります。
namespace ExceptionHandling
{
public class MyException : ApplicationException
{
public MyException(string message)
: base(message)
{
}
public MyException(string message, Exception innerException)
: base(message, innerException)
{
}
}
}
私の例外の 1 つは IntParseException です。このクラスは次のようになります。
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;
}
}
}
私のメインフォームでは、次のように例外を処理しています。
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");
}
}
例外をログに記録していますが、そのクラスは次のようになります。
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();
}
}
}
したがって、私の質問は、ログに記録する例外の種類を選択できるようにする例外に列挙型を追加するにはどうすればよいかということです。たとえば、ある時点ですべての例外をログに記録したいのですが、別の時点では userInputErrors のみをログに記録したいとします。