Home > Software design >  (.NET) Doing an Action when any exception is thrown
(.NET) Doing an Action when any exception is thrown

Time:11-23

Is there an effective way to essentially do something else when any exception is thrown in .NET 6?

Specifically, this is using Azure Functions v4 if that helps.

Essentially, If I have a function that throws due to a Null Reference Exception, is it possible to send an HTTP request before killing the program?

IE:

C#

public async Task<Exception> SendErrorMessage(Exception ex)
{
    _httpClient.PostAsync("https://myloggingurl.com/", new StringContent(ex.Message));
    return ex;
}

Essentially writing a solution that throws all exceptions through this method.

CodePudding user response:

Register for the AppDomain.CurrentDomain.UnhandledException.

This is a platform agnostic .Net event.

CodePudding user response:

Try this:

public async Task<Exception> SendErrorMessage(Exception ex)
        {
            try
            {
                _httpClient.PostAsync("https://myloggingurl.com/", new StringContent(ex.Message));
            }
            catch
            {
                throw ex;
            }
        }
  • Related