elsa-core/src/modules/Elsa.Http/Handlers/DefaultHttpEndpointWorkflowFaultHandler.cs

39 lines
1.4 KiB
C#
Raw Normal View History

using System.Net.Mime;
using System.Text.Json;
using Elsa.Http.Models;
using Elsa.Http.Services;
using Microsoft.AspNetCore.Http;
namespace Elsa.Http.Handlers;
2022-04-27 20:32:40 +00:00
// ReSharper disable once ClassWithVirtualMembersNeverInherited.Global
/// <summary>
/// A default fault handler that writes information about the fault to the <see cref="HttpResponse"/>.
/// </summary>
public class DefaultHttpEndpointWorkflowFaultHandler : IHttpEndpointWorkflowFaultHandler
{
/// <inheritdoc />
public virtual async ValueTask HandleAsync(HttpEndpointFaultedWorkflowContext context)
{
var httpContext = context.HttpContext;
var workflowInstance = context.WorkflowInstance;
var fault = workflowInstance.WorkflowState.Fault!;
httpContext.Response.ContentType = MediaTypeNames.Application.Json;
httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
var faultedResponse = JsonSerializer.Serialize(new
{
errorMessage = $"Workflow faulted at {workflowInstance.FaultedAt!} with error: {fault.Message}",
exception = fault.Exception,
workflow = new
{
name = workflowInstance.Name,
version = workflowInstance.Version,
instanceId = workflowInstance.Id
}
});
await httpContext.Response.WriteAsync(faultedResponse, context.CancellationToken);
}
}