using ECMJobRunner.Application.Common.Exceptions;
using ECMJobRunner.Application.ProfileHistories.Commands;
using ECMJobRunner.Domain.ValueObjects;
using MediatR;
using Microsoft.Extensions.Logging;
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
/// Logger for diagnostic output.
public class JobExceptionHandlingBehavior(ISender Sender, ILogger> Logger) : 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.ToString(),
AddedWho = "ECMJobRunner"
};
await Sender.Send(cmd, cancellationToken);
Logger.LogWarning(ex, "JobException caught in JobExceptionHandlingBehavior for ProfileId {ProfileId}, JobName {JobName}, ProcessName {ProcessName}, BatchId {BatchId}", ex.ProfileId, ex.JobName, ex.ProcessName, ex.BatchId);
return default!;
}
}
}