I have ASP MVC web application and trying to setup error logging where i am trying to display UI friendly message for web and log more detail message in database in need. My application might not need to log error message in DB always but i wanted to setup Custom Exception in a way so that it handles both scenario.
- Show short UI friendly message and log detail error message in DB
- Show short UI friendly message without logging in DB.
Here is what i have: CustomException: If detailMessage is passed, get new guid, log message in DB and concatenate guid value in shortMessage.
public class CustomException : Exception
{
public CustomException(string message) : base(message)
{
}
public CustomException(string shortMessage, string detailMessage = "") : base(shortMessage)
{
if (!string.IsNullOrWhiteSpace(detailMessage))
{
string loggingId = Guid.NewGuid().ToString();
//code to log in DB with detail message
shortMessage = $"Reference# : {loggingId}. {shortMessage}";
}
}
}
ThrowIf Helper Method to check value so that the code is cleaner and i don't need to do if block check as old school in web layer.
public static class ThrowIf
{
public static void IsZeroOrNegative(int argument, string shortMessage, string detailMessage = "")
{
if (argument <= 0)
{
throw new CustomException(shortMessage, detailMessage);
}
}
public static void IsNull(object argument, string shortMessage, string detailMessage = "")
{
if (argument == null)
{
throw CustomException.LogMessage(shortMessage, detailMessage);
}
}
}
Web layer code: (Please don't ask why i'm not throwing ArgumentException and using my own CustomException in this scenario)
public ActionResult GetEmployee(int employeeId)
{
var responseViewModel = new EmployeeModel();
try
{
ThrowIf.IsZeroOrNegative(employeeId, shortMessage: "This is short message for UI.", detailMessage: "This is detail message for DB");
}
catch(CustomException ex)
{
ViewBag.Error = ex.Message();
}
return View(responseViewModel);
}
Issue: As you can see in my CustomException code, if i pass value for 'detailMessage', it updates shortMessage with 'Reference..' text. Now in Web code, whenever the error happens, the text for ex.Message() doesn't contain 'Reference...' text and only shows 'This is short message for UI' instead of 'Reference# : [guid value]. This is short message for UI'.
Does anyone know why ex.Message is not displaying updated text when the error gets caught in Web layer?