0

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);
    }
}

enter image description here

Prosy Arceno
  • 2,616
  • 1
  • 8
  • 32
  • is it possible for you to put your method to execute in `catch(exception e){ method here }`? – Tiny Wang May 23 '23 at 06:31
  • I don't know if I got the question but I don't know if that's possible since I don't know if I can pass a flag to detect which block of code triggered the exception. Very new to C# and ASP.NEt – Prosy Arceno May 23 '23 at 06:42
  • I'm sorry that I can't get your point very well... – Tiny Wang May 23 '23 at 06:43

1 Answers1

1

How do I modify my exception middleware to still continue execution of this code below

You don't. Exception handling middleware is to late for such handling, it comes into play when the handler already finished (i.e. failed in this case). You need just to use standard exception handling with try-catch:

foreach (var record in records)
{
    InternalValidationResult internalValidationResult = null;
    try
    {
        internalValidationResult = await SecondModelDataTransfer(record.DataReceived);
    }
    catch (Exception e)
    {
        internalValidationResult = ...; // create the result
    }

    // 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);
}

See also:

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • yeah, i guess there's no other way around it. i just thought the exception middleware is the only one that should exist for all of the application – Prosy Arceno May 23 '23 at 23:32