.NET Core/6: Prevent .NET runtime from logging errors that are already handled in ExceptionFilter
We use Graylog to log everything, on Windows machines we also log into EventLog. I recently noticed for every exception in C# I got two items in EventViewer, one is Logged by our code, and the other is logged by the .net runtime I guess. It is a little bit annoying. TLDR; here's the answer:
public override void OnException(ExceptionContext actionExecutedContext)
{
_logger.Error(actionExecutedContext.Exception);
+ actionExecutedContext.ExceptionHandled = true;
actionExecutedContext.HttpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
actionExecutedContext.Result = new ObjectResult(new ErrorResponse()
{
StatusCode = (HttpStatusCode) StatusCodes.Status500InternalServerError,
Message = actionExecutedContext.Exception.Message,
});
base.OnException(actionExecutedContext);
}
The key is this line actionExecutedContext.ExceptionHandled = true;
.
Reference