Last active
December 14, 2023 02:51
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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