Skip to content

Middleware for exceptions handling #1039

@saguiitay

Description

@saguiitay

I've created a middleware to centrally handle various types of exceptions.
Before my change, I had a try-catch block in my TaskActivity.Execute() method:

protected override string Execute(TaskContext context, string input)
{
    try
    {
        ...
    }
    catch (BadExceptionType e)
    {
        throw new GoodExceptionType();
    }
}

This worked fine regarding retries when an exception is thrown.
However, when I moved this logic to a middleware, RetryOptions were disregarded, and the same activity was retried over-and-over indefinitely:

public override async Task Dispatch(DispatchMiddlewareContext context, Func<Task> next)
{
    try
    {
        await next();
    }
    catch (BadExceptionType e)
    {
        throw new GoodExceptionType();
    }
}

Is there some guidance on handling exceptions in middleware? Is there a correct way to handle this scenario?
I've tried simulating the behavior of the dispatcher, and managed to get this to work, but that feels incorrect:

public override async Task Dispatch(DispatchMiddlewareContext context, Func<Task> next)
{
    try
    {
        await next();
    }
    catch (Exception e)
    {
        var tfe = (TaskFailureException)e;

        var failureEvent = new TaskFailedEvent(-1, taskScheduledEvent.EventId, tfe!.InnerException!.Message, null, new FailureDetails(tfe!.InnerException));
        var result = new ActivityExecutionResult { ResponseEvent = failureEvent };
        context.SetProperty(result);
    }
}

@cgillum @davidmrdavid

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions