Question What is the difference between CustomExceptionFilter and GlobalExceptionHandler?

raysefo

Well-known member
Joined
Feb 22, 2019
Messages
361
Programming Experience
10+
Hi,

In my asp.net web API, I am using both GlobalExceptionHandler and CustomExceptionFilter. I think they do the same job, hiding the actual error from the client and send them "HTTP 500 - Internal Server Error. Please Contact your Administrator." response. I wonder if I remove GlobalExcepitonHandler and add Nlog into CustomExceptionFilter, can I still send the same response and log errors? What are your opinions?

UnhandledExceptionLogger can't catch all the errors that's why I would like to add logging inside of one of them.

CustomExceptionFilter:
C#:
public class CustomExceptionFilter : ExceptionFilterAttribute
    {

        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            base.OnException(actionExecutedContext);


            var response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
            {
                //Content = new StringContent("An unhandled exception was thrown by service."),
                ReasonPhrase = "HTTP 500 - Internal Server Error. Please Contact your Administrator."
            };

            actionExecutedContext.Response = response;
        }
    }

GlobalExceptionHandler:
C#:
public class GlobalExceptionHandler : ExceptionHandler
    {
        
        public override void Handle(ExceptionHandlerContext context)
        {
            var result = new HttpResponseMessage(HttpStatusCode.InternalServerError)
            {
                Content = new StringContent("HTTP 500 - Internal Server Error. Please Contact your Administrator."),
                ReasonPhrase = "Exception"
            };

            
            context.Result = new ErrorMessageResult(context.Request, result);
        }

        public class ErrorMessageResult : IHttpActionResult
        {
            private HttpRequestMessage _request;
            private readonly HttpResponseMessage _httpResponseMessage;

            public ErrorMessageResult(HttpRequestMessage request, HttpResponseMessage httpResponseMessage)
            {
                _request = request;
                _httpResponseMessage = httpResponseMessage;
            }

            public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
            {
                return Task.FromResult(_httpResponseMessage);
            }
        }

      }
UnhandledExceptionFilter:
C#:
public class UnhandledExceptionLogger : ExceptionLogger
    {
        private static readonly Logger logger = LogManager.GetCurrentClassLogger();

        public override void Log(ExceptionLoggerContext context)
        {
            var timestamp = DateTime.UtcNow;

            //NLOG
            NLog(logger, context.Exception, timestamp);
        }

        private void NLog(Logger logger, Exception message, DateTime timestamp)
        {
            var sb = new StringBuilder();
            sb.AppendLine(message.ToString());
            sb.AppendLine(timestamp.ToLongDateString());
            logger.Error(sb.ToString());
        }
    }
 
Considering that IIS is what is hosting your Web API, then it make sense that IIS has to be running from the time that a request is accepted by your Web API to the time you return a response for the request that was accepted. I don't know why you would consider to be wrong with IIS. What were you expecting to run your Web API code? Little hamsters running in their hamster wheels?
 
@Skydiver, I am not expecting hamsters to help but I wonder why it takes too much to process a request. At the beginning of the test, the duration was about 1 ms. I am just trying to make this work right and work better, of course with the help of you guys :)
 
For the fast responses, look at the corresponding HttpWebRequest calls.
 
it make sense that IIS has to be running from the time that a request is accepted by your Web API to the time you return a response
IIS should be running indefinitely, not just during queries. But for each request, there will be a new thread. Given you are executing parallel queries while load testing too, parallel or not, asynchronously or not, I'd imagine this would increase as progressive queries are executed. Almost all you need to know about IIS can be read IIS Web Server: (Internet Information Services)
Does something wrong with the IIS?
I think not. My guess would be if your server is slack on resources, CPU/Ram etc, consider feeding your hamster, so that it has enough to keep the wheels in motion. ;)
 
Last edited:
There is this answer on Concurrency Vs Parallelism : Topics | Popular You should note when you run chunks of code together, at the same time, this requires more resources. The difference of concurrency vs parallelism is explained a little better here : Concurrency, Parallelism, Threads, Processes, Async and Sync — Related? ? Running multiple chunks of code simultaneously will eat into the resources of your hardware if one chunk requires one thread, and another chunk requires its own thread. Food for thought if your server runs on a limited resource budget.
 
Back
Top Bottom