fix: handle exceptions in task

This commit is contained in:
Anna 2023-01-21 19:03:43 -05:00
parent 679b15821b
commit b9e8d4f79c
2 changed files with 27 additions and 17 deletions

View File

@ -3,6 +3,8 @@ using System.Net.Http.Headers;
namespace OrangeGuidanceTomestone.Helpers;
internal static class ServerHelper {
private static readonly HttpClient Client = new();
internal static HttpRequestMessage GetRequest(string? apiKey, HttpMethod method, string tail, string? contentType = null, HttpContent? content = null) {
if (!tail.StartsWith('/')) {
tail = '/' + tail;
@ -27,6 +29,6 @@ internal static class ServerHelper {
internal static async Task<HttpResponseMessage> SendRequest(string? apiKey, HttpMethod method, string tail, string? contentType = null, HttpContent? content = null) {
var req = GetRequest(apiKey, method, tail, contentType, content);
return await new HttpClient().SendAsync(req, HttpCompletionOption.ResponseHeadersRead);
return await Client.SendAsync(req, HttpCompletionOption.ResponseHeadersRead);
}
}

View File

@ -172,26 +172,34 @@ internal class Messages : IDisposable {
this.RemoveVfx(null, null);
Task.Run(async () => {
var resp = await ServerHelper.SendRequest(
this.Plugin.Config.ApiKey,
HttpMethod.Get,
$"/messages/{territory}"
);
var json = await resp.Content.ReadAsStringAsync();
var messages = JsonConvert.DeserializeObject<Message[]>(json)!;
await this.CurrentMutex.WaitAsync();
this.Current.Clear();
foreach (var message in messages) {
this.Current[message.Id] = message;
this.SpawnQueue.Enqueue(message);
try {
await this.DownloadMessages(territory);
} catch (Exception ex) {
PluginLog.LogError(ex, $"Failed to get messages for territory {territory}");
}
this.CurrentMutex.Release();
});
}
private async Task DownloadMessages(ushort territory) {
var resp = await ServerHelper.SendRequest(
this.Plugin.Config.ApiKey,
HttpMethod.Get,
$"/messages/{territory}"
);
var json = await resp.Content.ReadAsStringAsync();
var messages = JsonConvert.DeserializeObject<Message[]>(json)!;
await this.CurrentMutex.WaitAsync();
this.Current.Clear();
foreach (var message in messages) {
this.Current[message.Id] = message;
this.SpawnQueue.Enqueue(message);
}
this.CurrentMutex.Release();
}
private void RemoveVfx(object? sender, EventArgs? e) {
this.RemoveVfx();
}