Global Exception Handling and Logging in aspnet core webapi

Create a Model for your Error details as below:

public class ErrorDetails
	public int StatusCode { get; set; }
	public string Message { get; set; }

	public override string ToString()
		return JsonConvert.SerializeObject(this); //JsonConvert is part of Newtonsoft.Json package.

Create the Exception Factory which will handle Exceptions globally in your Api:

public static class ExceptionFactory
    public static void ConfigureExceptionHandler(this IApplicationBuilder app, int StatusCode = 0, string message = "")
        app.UseExceptionHandler(appError =>
            appError.Run(async context =>
                context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                context.Response.ContentType = "application/json";
                var contextFeature = context.Features.Get<IExceptionHandlerFeature>();
                if (contextFeature != null)
                    LogTraceFactory.LogError($"Something went wrong: {contextFeature.Error}");

                    await context.Response.WriteAsync(new ErrorDetails()
                        StatusCode = context.Response.StatusCode,
                        Message = "Internal Server Error."

Register Exception handling in your Api:

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
	if (env.IsDevelopment())

Also, you can return the error details in your Action Controllers as below:

public IActionResult GetproductDetails([FromQuery]int productId)
	LeadsProduct lead = null;
	if (productId == 0)
		LogTraceFactory.LogError($"Incorrect parameters, productId: {productId}");
		return BadRequest(new ErrorDetails { StatusCode = Convert.ToInt32(HttpStatusCode.BadRequest), Message = $"Missing parameters, productId: {productId} for product Leads." });

	lead = leadService.FetchProductDetails(productId);

	if (lead == null)
		LogTraceFactory.LogError($"product Leads Not Found for productId: {productId}");
		return NotFound(new ErrorDetails { StatusCode = Convert.ToInt32(HttpStatusCode.NotFound), Message = $"product Leads not found for productId {productId}." });

	return Ok(lead);

The example above uses the nlog package in the .net core Web Api. You can create LogTraceFactory class as below:

public static class LogTraceFactory
	private static ILogger logger = LogManager.GetCurrentClassLogger();

	public static void LogDebug(string message)

	public static void LogError(string message)

	public static void LogInfo(string message)

	public static void LogWarn(string message)

Configure nlog package as below in the nlog.config file:

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns=""

    <target name="logfile" xsi:type="File"
            layout="${longdate} ${level:uppercase=true} ${message}"/>

    <logger name="*" minlevel="Debug" writeTo="logfile" />

You can modify the above configuration as required. As part of the clean architecture, it is better to setup the ExceptionFactory and LogTraceFactory in the Common Layer of your Solution.

Omg! Now you can earn a six figure income. Click here to know how.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.