Skip to content

Instantly share code, notes, and snippets.

@dj-nitehawk
Last active December 14, 2023 02:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dj-nitehawk/a3e673479c8f3fb3660cb837f9032031 to your computer and use it in GitHub Desktop.
Save dj-nitehawk/a3e673479c8f3fb3660cb837f9032031 to your computer and use it in GitHub Desktop.
Adding/Throwing validation errors from within domain objects/services instead of using Results Pattern
using FastEndpoints;
using FastEndpoints.Swagger;
var bld = WebApplication.CreateBuilder();
bld.Services
.AddFastEndpoints()
.SwaggerDocument();
var app = bld.Build();
app.UseFastEndpoints()
.UseSwaggerGen();
app.Run();
sealed class Request
{
public bool IsHappyPath { get; set; }
}
sealed class Response
{
public string Message { get; set; }
}
sealed class TestEndpoint : Endpoint<Request, Response>
{
public override void Configure()
{
Get("test/{IsHappyPath}");
AllowAnonymous();
}
public override async Task HandleAsync(Request r, CancellationToken c)
{
var msg = HelloService.SayHello(r.IsHappyPath);
//if the hello service throws an error via ValidationContext,
//execution doesn't go past this point and an automatic 400 response is sent with the details.
//if the hello service simply adds errors instead of throwing,
//you can access the errors via this.ValidationFailures property:
await SendAsync(new()
{
Message = msg
});
}
}
sealed class HelloService
{
public static string SayHello(bool isHappyPath)
{
if (!isHappyPath)
{
//https://fast-endpoints.com/docs/validation#throwing-adding-errors-from-anywhere
var valCtx = ValidationContext.Instance;
valCtx.ThrowError("I am unhappy!");
}
return "Hello world!";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment