Recently I created a class that would manager errors, log them, and write details about them to files when the function logError
was called. It would be done by having an error code and error message and then displaying the error to the console and writing it to the file if the user wanted to.
I just posted this here to see if there was any way I can improve the class.
using log4net;
using System;
using System.Collections.Generic;
namespace Kiwi.Application.Base.Error
{
sealed class ErrorManager
{
private readonly Dictionary<string, string> errorCodes;
private readonly ILog myLogger;
public ErrorManager()
{
errorCodes = new Dictionary<string, string>();
myLogger = LogManager.GetLogger(typeof(ErrorManager));
// Add some errors and their messages to the dictionary
errorCodes.Add("bn1x", "Error when beginning to listen on server socket.");
errorCodes.Add("dm9e", "Unable to locate the error log file.");
}
public void logError(string errorCode, bool writeErrorToFile = false)
{
string errorMessage;
if (errorCodes.TryGetValue(errorCode, out errorMessage))
{
myLogger.Warn(errorMessage);
if (writeErrorToFile)
logToFile(errorCode);
}
else
{
logUnhandeldError("[Error code " + errorCode + "] " + errorCode);
}
}
private void logUnhandeldError(string errorCode)
{
myLogger.Error("Unhandeld error " + errorCode);
}
private void logToFile(string errorCode = "", string fileName = "logs/error.log")
{
try
{
using (System.IO.StreamWriter file = new System.IO.StreamWriter(fileName, true))
{
file.WriteLine("Error " + errorCode + " logged at " + getErrorTimestamp());
file.WriteLine("Message: " + tryGetErrorMessage(errorCode));
}
}
catch (System.IO.FileNotFoundException)
{
logError("dm9e");
}
}
private string getErrorTimestamp()
{
return DateTime.Now.ToLongDateString();
}
private string tryGetErrorMessage(string errorCode)
{
string errorMessage;
if (errorCodes.TryGetValue(errorCode, out errorMessage))
return errorMessage;
else return "";
}
}
}