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

Time:02-10

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?

CodePudding user response:

Create a custom Exception class where you can set Name & Place as properties. In the Worker, add a try catch block around the code that may throw an exception. Create and throw your custom exception, setting the original exception as the InnerException (https://docs.microsoft.com/en-us/dotnet/api/system.exception.innerexception?view=net-6.0)

Then in your handler get the name / place from the wrapper exception, and then use the InnerException for the rest.

  •  Tags:  
  • Related