1

I am trying to learn how to throw exceptions.

Currently when I do the following

        try
        {
            throw new InvalidOperationException("TEST");
        }
        catch
        {
                throw;
        }

When I look into AI the exception comes like this:#

InvalidOperationException

enter image description here

with a message "Test"

How do I get it to throw something like the below?

System.InvalidOperationException: TEST at test.Program.Main

enter image description here

user3622142
  • 360
  • 4
  • 18
  • 1
    `Exception` comes with a `StackTrace` property https://learn.microsoft.com/en-us/dotnet/api/system.exception.stacktrace?view=net-5.0 that indicates where it was thrown from. Is this what you are looking for? – moreON Mar 05 '21 at 00:06
  • adding this extra information into application insights logs? – Ivan Glasenberg Mar 08 '21 at 09:20

1 Answers1

0

As moreON said in the comment, you could get where the exception thrown from with Exception.StackTrace property.

try
{
    throw new InvalidOperationException("TEST");
}
catch(InvalidOperationException e)
{
    throw new InvalidOperationException(e.Message + e.StackTrace);
}

Or you can get the current project name/file name/method name/line number. And it throws like this: System.InvalidOperationException: ProjetName.FileName.MethodName(LineNumber): TEXT.

private static string Log(string text,
                [CallerFilePath] string file = "",
                [CallerMemberName] string member = "",
                [CallerLineNumber] int line = 0)
{
    return Assembly.GetCallingAssembly().GetName().Name+"."+Path.GetFileName(file)+"."+member+"("+line + "): " + text;
}

// throw exception
try
{
    
    throw new InvalidOperationException(Log("Test"));
}
catch(InvalidOperationException e)
{
    throw;
}
unknown
  • 6,778
  • 1
  • 5
  • 14