| | | 1 | | using System.Net.Mime; |
| | | 2 | | using Elsa.Workflows; |
| | | 3 | | using Microsoft.AspNetCore.Http; |
| | | 4 | | |
| | | 5 | | namespace Elsa.Http.Handlers; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// A fault handler that writes detailed information about the fault to the <see cref="HttpResponse"/>. |
| | | 9 | | /// </summary> |
| | | 10 | | public sealed class DetailedHttpEndpointFaultHandler : IHttpEndpointFaultHandler |
| | | 11 | | { |
| | | 12 | | private readonly IApiSerializer _apiSerializer; |
| | | 13 | | |
| | | 14 | | /// <summary> |
| | | 15 | | /// Initializes a new instance of the <see cref="DefaultHttpEndpointFaultHandler"/> class. |
| | | 16 | | /// </summary> |
| | 0 | 17 | | public DetailedHttpEndpointFaultHandler(IApiSerializer apiSerializer) |
| | | 18 | | { |
| | 0 | 19 | | _apiSerializer = apiSerializer; |
| | 0 | 20 | | } |
| | | 21 | | |
| | | 22 | | /// <inheritdoc /> |
| | | 23 | | public async ValueTask HandleAsync(HttpEndpointFaultContext context) |
| | | 24 | | { |
| | 0 | 25 | | var httpContext = context.HttpContext; |
| | 0 | 26 | | var workflowState = context.WorkflowState; |
| | 0 | 27 | | var isTimeoutIncident = GetIsTimeoutFault(context); |
| | 0 | 28 | | var statusCode = isTimeoutIncident ? StatusCodes.Status408RequestTimeout : StatusCodes.Status500InternalServerEr |
| | | 29 | | |
| | 0 | 30 | | httpContext.Response.ContentType = MediaTypeNames.Application.Json; |
| | 0 | 31 | | httpContext.Response.StatusCode = statusCode; |
| | | 32 | | |
| | 0 | 33 | | var faultedResponse = _apiSerializer.Serialize(workflowState); |
| | 0 | 34 | | await httpContext.Response.WriteAsync(faultedResponse, context.CancellationToken); |
| | 0 | 35 | | } |
| | | 36 | | |
| | | 37 | | private bool GetIsTimeoutFault(HttpEndpointFaultContext context) |
| | | 38 | | { |
| | 0 | 39 | | var workflowState = context.WorkflowState; |
| | 0 | 40 | | var exceptionTypes = new[] { typeof(OperationCanceledException), typeof(TaskCanceledException), typeof(TimeoutEx |
| | 0 | 41 | | var timeoutIncident = workflowState.Incidents.FirstOrDefault(x => exceptionTypes.Contains(x.Exception?.Type)); |
| | | 42 | | |
| | 0 | 43 | | return timeoutIncident != null; |
| | | 44 | | } |
| | | 45 | | } |