Search code examples
c#.net.net-corenlog.net-core-service-worker

How to get the values from inside the code when exception occurs?


I have a worker service in .net core 3.1 in my Program.cs i have the below codes

   public static void Main(string[] args)
    {
        try
        {
            CreateHostBuilder(args).Build().Run();
        }
        catch(Exception ex)
        {
            Handler(ex);
        }
       
    }

 static void Handler( Exception e)
    {
        var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
        List<Test> _Test = new List<Test>()
        {
            new Test()
            {
                  
            }
        };
        LogEventInfo eventInfo = new LogEventInfo
        {
            Level = LogLevel.Error,
            Properties = { { "Application",_Test } }
        };
        logger.Log(eventInfo);  
    }

private class Test
{
 public string Name{get;set;}
 public string Place{get;set;}
}

In my worker class i have code as below

public class Worker : BackgroundService
{ 
  
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        
        do
        {
           
           string Name  ="MyName";// These values will be fetched from different file
           string Place="MyPlace";
        //Some Logic where an exception may occur
        }
        while (!stoppingToken.IsCancellationRequested);

    }
}

Is there anyway to get the values of Name and Place of worker class to Handler method in program class when an exception arises. Since I'm thinking of a global exception handler I'm thinking of not putting any more try catch blocks. I want to handle all the exception with the try catch in the program.cs file. How can i get the Name and Place values onto my handler on such scenario so that it can be logged?


Solution

  • While a custom exception is a possibility, you could also simply decorate any exception thrown inside your service with those properties using the Data property:

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        do
        {
            string Name = "MyName";
            string Place = "MyPlace";
    
            try
            {
                //Some Logic where an exception may occur
            }
            catch (Exception e)
            {
                e.Data["Name"] = Name;
                e.Data["Place"] = Place;
                throw;
            }
        }
        while (!stoppingToken.IsCancellationRequested);
    }