I’m writing a blazor WASM app, and found myself writing the same boilerplate code for notifying errors in API calls over and over, making my code messy and hard to read. I’m thinking of replacing that repeated code with calls to this, but I’m new to Blazor and I’m not sure whether I’m making a mistake here. Could anyone who knows more than I do have a look and let me know if you think this is a reasonable plan?
I’ve created a Scoped service, which I inject in program.cs
using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
using NeuroCare.Shared.Models;
using Radzen;
using System.Net.Http.Json;
namespace NeuroCare.BlazorWASM.Services
{
public class APIHelper
{
private HttpClient _httpClient;
private NotificationService _notificationService;
private const string url_getconsentforms = "/api/v1/consent/forms/All";
public APIHelper(HttpClient httpClient, NotificationService notificationService)
{
_httpClient = httpClient;
_notificationService = notificationService;
}
public async Task <ConsentForms?> GetConsentForms(string Module)
{
HttpClientWithNotification< ConsentForms> _httpClientWithNotification = new();
ConsentForms? cf = await _httpClientWithNotification.HttpGet(_httpClient, _notificationService, url_getconsentforms);
return cf;
}
private class HttpClientWithNotification<T>() where T : new()
{
public async Task<T?> HttpGet(HttpClient httpClient, NotificationService notificationService, string url)
{
T? getResult = new();
try
{
getResult = await httpClient.GetFromJsonAsync<T>(url);
}
catch (HttpRequestException e)
{
if (e.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
notificationService.Notify(new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "Unauthorized", Detail = "You are not authorized to perform this action", Duration = 4000 });
}
throw;
}
catch (AccessTokenNotAvailableException exception)
{
exception.Redirect();
}
catch (Exception e)
{
notificationService.Notify(new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "Unexpected error", Detail = e.Message, Duration = 4000 });
throw;
}
return getResult;
}
}
}
}
So when I need to call the API, I can just call the right method in APIHelper, which will use the generic class to do the actual http call, and do the notification, making my actual blazor components much cleaner. Does this look like a good idea? – it seems like a winner to me, but could be wrong.
(I know my capitalization and style is a bit messy)
Cheers
Rich