Custom Exception
First try to indentify why you want Custom Exception, Custom Exceptions are basically used to intimate the ui, when there is a violation in your busniess logic,
you can use custom exception or business oriented exception in your business logic
A user makes an order and when the order qunatity is greater than the available stock.
function PlaceOrder(int OrderQuantity { if (Stock > (OrderQuantity + MinimumStock)) { //Place Order } else { throw InAdequateStockException(...) } }
These exceptions need to be handled in the layer above, that's generally in your code behind.
When caught, below are the possible excepion handlers
Alert the user. In the above scenario, user must be intimated that the order can't be completed Alternate Action. Purchase department need to intimated of less stock. So in catch block you can write som code to update the purchase dept. Log the exception Generally business exceptions are not logged, they are either intimated to user or alternate action is done. Rest all excepions are logged to the some media
try { PlaceOrder(OrderQuantity); } catch(InAdequateStockException e) { // Intimate Purchase Department about stock unavailability // Also If Requried, Log error Logger.LogError(e.Message); }
Logging
Logging can be done to a flat text, to database or send an email. Basic logging can done be creating a file stream and writing the exception information to the stream.
public class Logger { public static void LogError(string sErrMsg) { //sLogFormat used to create log files format : // dd/mm/yyyy hh:mm:ss AM/PM ==> Log Message string sLogFormat = DateTime.Now.ToShortDateString().ToString()+" "+DateTime.Now.ToLongTimeString().ToString()+" ==> "; //this variable used to create log filename format " //for example filename : ErrorLogYYYYMMDD string sYear = DateTime.Now.Year.ToString(); string sMonth = DateTime.Now.Month.ToString(); string sDay = DateTime.Now.Day.ToString(); sErrorTime = sYear+sMonth+sDay;
StreamWriter sw = new StreamWriter(sPathName+sErrorTime,true); sw.WriteLine(sLogFormat + sErrMsg); sw.Flush(); sw.Close(); } }
Lot of third party logging mechanism for DotNet is available free like Log4Net and NLog.
|
No responses found. Be the first to respond and make money from revenue sharing program.
|