using ECMJobRunner.Application.Common.Exceptions; using ECMJobRunner.Application.ProfileHistories.Commands; using ECMJobRunner.Domain.ValueObjects; using MediatR; using System.Threading; using System.Threading.Tasks; namespace ECMJobRunner.Application.Profiles.Commands.Behaviors; /// /// Pipeline behavior that catches exceptions, /// persists a profile history error record and re-throws the exception /// /// The type of the MediatR request /// The type of the MediatR response /// MediatR sender used to dispatch the public class JobExceptionHandlingBehavior(ISender Sender) : IPipelineBehavior where TRequest : notnull { /// /// Handles the pipeline behavior /// Executes main query if request is TriggeringDEXJobCommand /// #if NET48 public async Task Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate next) #else public async Task Handle(TRequest request, RequestHandlerDelegate next, CancellationToken cancellationToken) #endif { try { return await next(); } catch (JobException ex) { var cmd = new CreateProfileHistoryCommand() { ProfileId = ex.ProfileId, Result = ResultType.Ok, ResultText = ex.Message, AddedWho = "ECMJobRunner" }; await Sender.Send(cmd, cancellationToken); throw; } } }