I have this code that I use to log activity to the Cosmos DB.
protected override async void OnStart()
{
await Helper.LogActivity("OnStart");
public static partial class Helper
{
public static async Task LogActivity(string activity)
{
var logItem = new LogItem()
{
Activity = activity,
};
await CosmosDBService.InsertLogItem(logItem);
}
}
public class CosmosDBService
{
static DocumentClient docClient = null;
static readonly string databaseName = "Test";
static readonly string collectionName = "Logs";
static async Task<bool> Initialize()
{
if (docClient != null)
return true;
try
{
docClient = new DocumentClient(new Uri(APIKeys.CosmosEndpointUrl), APIKeys.CosmosAuthKey);
}
catch (Exception ex)
{
Debug.WriteLine(ex);
docClient = null;
return false;
}
return true;
}
public async static Task InsertLogItem(LogItem item)
{
if (!await Initialize())
return;
await docClient.CreateDocumentAsync(
UriFactory.CreateDocumentCollectionUri(databaseName, collectionName),
item);
}
}
What I am concerned with is if there was no internet connection. Would it be a good idea to somehow test for this first or should I add some try catch exception to the code for the logging?
Would appreciate any suggestions on how I could make this code bullet proof so that even if there is no connection then there is no exception thrown in the OnStart.
If the logging fails then it's not a problem for me but I want to be sure the code will not fail if there is no internet connection or if the cosmos db call fails.