44 lines
1.4 KiB
C#
44 lines
1.4 KiB
C#
using Microsoft.AspNetCore.Components;
|
|
using Prefab.Web.Client.Models.Shared;
|
|
using Prefab.Web.Client.Services;
|
|
|
|
namespace Prefab.Web.Client.Pages;
|
|
|
|
public abstract class ResultComponentBase<T> : ComponentBase
|
|
{
|
|
[Inject]
|
|
protected INotificationService NotificationService { get; set; } = null!;
|
|
|
|
protected async Task<Result<T>> Execute(
|
|
Func<CancellationToken, Task<Result<T>>> operation,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
try
|
|
{
|
|
var result = await operation(cancellationToken);
|
|
|
|
if (!result.IsSuccess && result.Problem is { } problem)
|
|
{
|
|
var message = string.IsNullOrWhiteSpace(problem.Detail)
|
|
? problem.Title ?? "An unexpected error occurred."
|
|
: problem.Detail;
|
|
|
|
NotificationService.ShowError(message);
|
|
}
|
|
|
|
return result;
|
|
}
|
|
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
|
{
|
|
throw;
|
|
}
|
|
catch (Exception exception)
|
|
{
|
|
var problem = ResultProblem.Unexpected("Failed to complete the requested operation.", exception);
|
|
var fallback = problem.Detail ?? problem.Title ?? "Failed to complete the requested operation.";
|
|
NotificationService.ShowError(fallback);
|
|
return Result<T>.Failure(problem);
|
|
}
|
|
}
|
|
}
|