add exception handling to `ApiWebService`

improve ``BanCommand`` API response handling
This commit is contained in:
Alan Moon 2025-03-02 15:54:49 -08:00
parent 1edbbde74c
commit aa85aeab32
2 changed files with 23 additions and 9 deletions

View File

@ -1,5 +1,6 @@
using System;
using System.Net.Http.Json;
using sodoffmmo.CommandHandlers;
namespace sodoffmmo.Core;
@ -15,12 +16,16 @@ public class ApiWebService
);
httpClient.Timeout = new TimeSpan(0, 0, 3);
try
{
var response = httpClient.PostAsync($"{Configuration.ServerConfiguration.ApiUrl}/Moderation/CheckForVikingBan", content).Result;
Log("Moderation/CheckForVikingBan");
if (response.StatusCode == System.Net.HttpStatusCode.OK && response.Content != null) return response.Content.ReadFromJsonAsync<UserBanType>().Result;
else return null;
} catch (Exception e) { LogError(e.Message); return null; }
}
public HttpResponseMessage BanUser(Client client, string userId, string banType, string days)
public string? BanUser(Client client, string userId, string banType, string days)
{
HttpClient httpClient = new();
var content = new FormUrlEncodedContent(
@ -32,7 +37,18 @@ public class ApiWebService
}
);
httpClient.Timeout = new TimeSpan(0, 0, 3);
try
{
var response = httpClient.PostAsync($"{Configuration.ServerConfiguration.ApiUrl}/Moderation/AddBanToVikingByGuid", content).Result;
return response;
Log("Moderation/AddBanToVikingByGuid");
if (response.StatusCode == System.Net.HttpStatusCode.OK && response.Content != null) return response.Content.ReadAsStringAsync().Result;
else return null;
} catch (Exception e) { LogError(e.Message); return null; }
}
private void Log(string endpoint) => Console.WriteLine($"Sent API Request To {Configuration.ServerConfiguration.ApiUrl}/{endpoint}");
private void LogError(string message) => Console.WriteLine($"An Error Has Occured When Sending An API Request - {message}");
}

View File

@ -19,10 +19,8 @@ class BanCommand : IManagementCommand
// send an http request to the api set in appsettings
ApiWebService apiWebService = new();
var response = apiWebService.BanUser(client, clientToBan, arguments[1], arguments[2]);
var responseString = response.Content.ReadAsStringAsync().Result;
if (response.StatusCode != System.Net.HttpStatusCode.OK && responseString != null) { client.Send(Utils.BuildServerSideMessage(responseString, "Server")); return; }
else if (responseString != null) { client.Send(Utils.BuildServerSideMessage("User Banned Successfully", "Server")); return; }
if (response != null) { client.Send(Utils.BuildServerSideMessage("User Banned Successfully", "Server")); return; }
else { client.Send(Utils.BuildServerSideMessage("Empty Response", "Server")); }
}
}