How do I modify my exception middleware to still continue execution of this code below:
public async Task<MessageResponseModel> TransferSecondModelData()
{
//get the untransferred records and prep for transfer
List <SecondModel> records = _dbContext.SecondModel.Where(X => X.Transfered == Constants.TO_TRANSFER).ToList();
// init validation results to return invalid data
List<InternalValidationResult> internalValidationResults = new() { };
foreach (var record in records)
{
//if the transfer was successful, 1: transferred
//else, 2: attempted and failed
// This method transfers the data to the FirstModel
// THIS IS WHERE IT GETS PROBLEMATIC SINCE THE SecondModel.DataReceived can accept any inputs.
// INVALID DATA already exists. and if this program gets to this code, my ExceptionMiddleware throws an exception and halts the execution.
InternalValidationResult internalValidationResult = await SecondModelDataTransfer(record.DataReceived);
// this just checks the validation if isValid
record.Transfered = internalValidationResult.AdditionalDetails.IsValid ? Constants.TRANSFER_SUCCESS: Constants.TRANSFER_FAILED;
// add if success or failed
internalValidationResults.Add(internalValidationResult);
}
//save the changes
await _dbContext.SaveChangesAsync();
await _db2Context.SaveChangesAsync();
// return success message
MessageResponseModel messageResponse = new ()
{
StatusCode = StatusCodes.Status200OK,
Type = HttpResponses.SUCCESS
};
return messageResponse;
}
Exception Middleware:
public class ExceptionMiddleware
{
private readonly RequestDelegate _next;
public ExceptionMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext httpContext)
{
try
{
await _next(httpContext);
}
catch (Exception exception)
{
await HandleExceptionAsync(httpContext, exception);
}
}
private static async Task HandleExceptionAsync(HttpContext httpContext, Exception exception)
{
httpContext.Response.ContentType = "application/json";
httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
var response = new MessageResponseModel
{
StatusCode = StatusCodes.Status500InternalServerError,
Type = exception.GetType().Name,
Message = exception.Message,
AdditionalDetails = exception.InnerException?.Message
}.ToString();
await httpContext.Response.WriteAsync(response);
}
}