| | | 1 | | using Elsa.Common; |
| | | 2 | | using Elsa.Workflows.Models; |
| | | 3 | | using Elsa.Workflows.Pipelines.WorkflowExecution; |
| | | 4 | | using Elsa.Workflows.State; |
| | | 5 | | using Microsoft.Extensions.Logging; |
| | | 6 | | |
| | | 7 | | namespace Elsa.Workflows.Middleware.Workflows; |
| | | 8 | | |
| | | 9 | | /// <summary> |
| | | 10 | | /// Adds extension methods to <see cref="ExceptionHandlingMiddleware"/>. |
| | | 11 | | /// </summary> |
| | | 12 | | public static class ExceptionHandlingMiddlewareExtensions |
| | | 13 | | { |
| | | 14 | | /// <summary> |
| | | 15 | | /// Installs the <see cref="ExceptionHandlingMiddleware"/> component in the activity execution pipeline. |
| | | 16 | | /// </summary> |
| | | 17 | | public static IWorkflowExecutionPipelineBuilder UseExceptionHandling(this IWorkflowExecutionPipelineBuilder pipeline |
| | | 18 | | } |
| | | 19 | | |
| | | 20 | | /// <summary> |
| | | 21 | | /// Catches any exceptions thrown by downstream components and transitions the workflow into the faulted state. |
| | | 22 | | /// </summary> |
| | | 23 | | public class ExceptionHandlingMiddleware : IWorkflowExecutionMiddleware |
| | | 24 | | { |
| | | 25 | | private readonly WorkflowMiddlewareDelegate _next; |
| | | 26 | | private readonly ISystemClock _systemClock; |
| | | 27 | | private readonly ILogger<ExceptionHandlingMiddleware> _logger; |
| | | 28 | | |
| | | 29 | | /// <summary> |
| | | 30 | | /// Constructor. |
| | | 31 | | /// </summary> |
| | 425 | 32 | | public ExceptionHandlingMiddleware(WorkflowMiddlewareDelegate next, ISystemClock systemClock, ILogger<ExceptionHandl |
| | | 33 | | { |
| | 425 | 34 | | _next = next; |
| | 425 | 35 | | _systemClock = systemClock; |
| | 425 | 36 | | _logger = logger; |
| | 425 | 37 | | } |
| | | 38 | | |
| | | 39 | | /// <inheritdoc /> |
| | | 40 | | public async ValueTask InvokeAsync(WorkflowExecutionContext context) |
| | | 41 | | { |
| | | 42 | | try |
| | | 43 | | { |
| | 440 | 44 | | await _next(context); |
| | 440 | 45 | | } |
| | 0 | 46 | | catch (Exception e) |
| | | 47 | | { |
| | 0 | 48 | | _logger.LogWarning(e, "An exception was caught from a downstream middleware component"); |
| | 0 | 49 | | var exceptionState = ExceptionState.FromException(e); |
| | 0 | 50 | | var now = _systemClock.UtcNow; |
| | 0 | 51 | | var activity = context.Workflow; |
| | 0 | 52 | | var incident = new ActivityIncident(activity.Id, activity.NodeId ,activity.Type, e.Message, exceptionState, |
| | 0 | 53 | | context.Incidents.Add(incident); |
| | 0 | 54 | | context.TransitionTo(WorkflowSubStatus.Faulted); |
| | 0 | 55 | | context.AddExecutionLogEntry("Faulted", e.Message, exceptionState); |
| | 0 | 56 | | } |
| | 440 | 57 | | } |
| | | 58 | | } |