- public void ParentFunction()
- {
- try
- {
- this.ChildFunction();
- Console.WriteLine("After Exception");
- }
- catch (Exception ex)
- {
- }
- }
- public void ChildFunction()
- {
- try
- {
- this.GrandChildFunction();
- Console.WriteLine("Child Function");
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- public void GrandChildFunction()
- {
- try
- {
- int x = 10, y = 0;
- Console.WriteLine(x / y);
- Console.WriteLine("Grand Child Function");
- }
- catch (Exception ex)
- {
- throw;
- }
- }
In the above code, parent function is calling child function and child function is calling grandchild function internally. The exception is actually happening in the grandchild level, same as throwing to its parent, which is child function. But child function, wrapped with the exception object, is throwing to its parent. In this scenario, the actual stack trace is lost.
- public DateTime? GetDateTime(SqlDataReader reader, string columnName)
- {
- DateTime? value = null;
- try
- {
- value = DateTime.Parse(reader[columnName].ToString());
- }
- catch
- {
- }
- return value;
- }
Extra overhead to manage the bad code
- /// <summary>
- /// This class is used for handle the custom exception in the application level.
- /// </summary>
- public class CustomExceptionHandler : IExceptionFilter
- {
- public void OnException(ExceptionContext context)
- {
- throw new NotImplementedException();
- }
- }
- /// <summary>
- /// This class will allow to generate the custom exception message.
- /// </summary>
- public class CustomException : Exception
- {
- public CustomException()
- {
- }
- public CustomException(string message) : base(message)
- {
- }
- public CustomException(string message, string responseModel) : base(message)
- {
- }
- public CustomException(string message, Exception innerException) : base(message, innerException)
- {
- }
- }
- /// <summary>
- /// Different types of exceptions.
- /// </summary>
- public enum Exceptions
- {
- NullReferenceException = 1,
- FileNotFoundException = 2,
- OverflowException = 3,
- OutOfMemoryException = 4,
- InvalidCastException = 5,
- ObjectDisposedException = 6,
- UnauthorizedAccessException = 7,
- NotImplementedException = 8,
- NotSupportedException = 9,
- InvalidOperationException = 10,
- TimeoutException = 11,
- ArgumentException = 12,
- FormatException = 13,
- StackOverflowException = 14,
- SqlException = 15,
- IndexOutOfRangeException = 16,
- IOException = 17
- }
- /// <summary>
- /// This method will return the status code based on the exception type.
- /// </summary>
- /// <param name="exceptionType"></param>
- /// <returns>HttpStatusCode</returns>
- private HttpStatusCode getErrorCode(Type exceptionType)
- {
- Exceptions tryParseResult;
- if (Enum.TryParse<Exceptions>(exceptionType.Name, out tryParseResult))
- {
- switch (tryParseResult)
- {
- case Exceptions.NullReferenceException:
- return HttpStatusCode.LengthRequired;
- case Exceptions.FileNotFoundException:
- return HttpStatusCode.NotFound;
- case Exceptions.OverflowException:
- return HttpStatusCode.RequestedRangeNotSatisfiable;
- case Exceptions.OutOfMemoryException:
- return HttpStatusCode.ExpectationFailed;
- case Exceptions.InvalidCastException:
- return HttpStatusCode.PreconditionFailed;
- case Exceptions.ObjectDisposedException:
- return HttpStatusCode.Gone;
- case Exceptions.UnauthorizedAccessException:
- return HttpStatusCode.Unauthorized;
- case Exceptions.NotImplementedException:
- return HttpStatusCode.NotImplemented;
- case Exceptions.NotSupportedException:
- return HttpStatusCode.NotAcceptable;
- case Exceptions.InvalidOperationException:
- return HttpStatusCode.MethodNotAllowed;
- case Exceptions.TimeoutException:
- return HttpStatusCode.RequestTimeout;
- case Exceptions.ArgumentException:
- return HttpStatusCode.BadRequest;
- case Exceptions.StackOverflowException:
- return HttpStatusCode.RequestedRangeNotSatisfiable;
- case Exceptions.FormatException:
- return HttpStatusCode.UnsupportedMediaType;
- case Exceptions.IOException:
- return HttpStatusCode.NotFound;
- case Exceptions.IndexOutOfRangeException:
- return HttpStatusCode.ExpectationFailed;
- default:
- return HttpStatusCode.InternalServerError;
- }
- }
- else
- {
- return HttpStatusCode.InternalServerError;
- }
- }
In the above method, I have mapped the exceptions to relevant status codes. This is just a sample. You can use your own mapping based on your requirement.
- /// <summary>
- /// This method will automatically trigger when any exception occurs in application level.
- /// </summary>
- /// <param name="context"></param>
- public void OnException(ExceptionContext context)
- {
- HttpStatusCode statusCode = (context.Exception as WebException != null &&
- ((HttpWebResponse) (context.Exception as WebException).Response) != null) ?
- ((HttpWebResponse) (context.Exception as WebException).Response).StatusCode
- : getErrorCode(context.Exception.GetType());
- string errorMessage = context.Exception.Message;
- string customErrorMessage = Constant.ERRORMSG;
- string stackTrace = context.Exception.StackTrace;
- HttpResponse response = context.HttpContext.Response;
- response.StatusCode = (int) statusCode;
- response.ContentType = "application/json";
- var result = JsonConvert.SerializeObject(
- new
- {
- message = customErrorMessage,
- isError = true,
- errorMessage = errorMessage,
- errorCode = statusCode,
- model = string.Empty
- });
- #region Logging
- //if (ConfigurationHelper.GetConfig()[ConfigurationHelper.environment].ToLower() != "dev")
- //{
- // LogMessage objLogMessage = new LogMessage()
- // {
- // ApplicationName = ConfigurationHelper.GetConfig()["ApplicationName"].ToString(),
- // ComponentType = (int) ComponentType.Server,
- // ErrorMessage = errorMessage,
- // LogType = (int) LogType.EventViewer,
- // ErrorStackTrace = stackTrace,
- // UserName = Common.GetAccNameDev(context.HttpContext)
- // };
- // LogError(objLogMessage, LogEntryType.Error);
- //}
- #endregion Logging
- response.ContentLength = result.Length;
- response.WriteAsync(result);
- }
In the above method I have commented a region called logging which is used for logging in event viewer in my application. You can use your own logging mechanism,
- HttpStatusCode is used to get the exact status code for all web exceptions and customized exceptions.
- ErrorMessage is used for storing the exact error message.
- CustomErrorMessage is used to return the customized error message, here I have used as constant.
- StackTrace is used to log the stack trace of the exception, which will be helpful for troubleshooting the issue for the developers.
- The response is used for returning the response to the client.
- By using JsonConvert class you can serialize the response model into JSON which you need to write to respond. You can wrap up your own response format based on your need.
- /// <summary>
- /// This method gets called by the runtime. Use this method to add services to the container.
- /// </summary>
- /// <param name="services"></param>
- public void ConfigureServices(IServiceCollection services)
- {
- // Add CORS to the web api application
- AppStart.RegisterCORS(ref services);
- // Add framework services.
- services.AddMvc(
- config =>
- {
- config.Filters.Add(typeof(CustomExceptionHandler));
- config.Filters.Add(typeof(ValidationFilter));
- }
- ).AddFluentValidation();
- // Register custom services
- AppStart.RegisterDIClasses(ref services);
- AppStart.RegisterSwagger(ref services);
- AppStart.ConfigureModelValidation(ref services);
- }

dheeraj guptaPosted Dec 25, 2019, 3:09 AM
Just one question there is error in line Constant.ERRORMSG. Have you created any custom class with name "Constant" in which ERRORMSG property is defined because VS2017 is suggesting System.Reflection.Metadata to remove the error. I am using Asp.Net Core 2.2 framework. Please help me. Thanks in advance
prashant patvariPosted Oct 7, 2019, 1:53 AM
Above this line error coming string customErrorMessage = Constant.ERRORMSG;
Vasanth RPosted Sep 9, 2019, 8:01 AM
It's nice., But I'm a beginner in this concept, could you please share the downloadable sample project
rami reddyPosted Mar 26, 2019, 2:45 AM
Its very good article, can u help me in .net core 2.1
Abhishek MishraPosted Oct 26, 2018, 7:47 AM
Good one :)