Usage Examples
These examples demonstrate how Result enables expressive, composable error handling through railway-oriented programming.
Basic Builder Usage
// Fluent builder with compile-time safety
var result = ResultFactory.Problem<string>()
.WithSourceId("TestSource")
.WithTitle("Test Title")
.WithDetail("Test Detail")
.WithStatusCode(HttpStatusCode.BadRequest)
.Create();
// Pre-set SourceId for convenience
var result2 = ResultFactory.Problem<string>("TestSource")
.WithTitle("Not Found")
.WithDetail("Resource not found")
.WithStatusCode(HttpStatusCode.NotFound)
.Create();
Named Tuple Approach
// Shorthand factory using named tuple
var result3 = ResultFactory.Problem<string>(
"TestSource",
("Error Title", "Error detail",
HttpStatusCode.BadRequest));
Common Errors
// Pre-defined common error patterns
var notFound = ResultFactory.Common.NotFound<string>(
"MySource",
"User not found");
var badRequest = ResultFactory.Common.BadRequest<User>(
"UserService",
"Invalid user data");
var serverError = ResultFactory.Common
.InternalServerError<Order>(
"OrderService",
"Database connection failed");
Railway-Oriented Pipeline
// Complete pipeline demonstrating composition
return await GetUserAsync(userId)
.EnsureAsync(
user => user.IsActive,
() => ResultFactory.Common.BadRequest<User>(
"UserService",
"User is inactive"))
.MapAsync(user => new UserDto(user))
.FlatMapAsync(dto => SaveToCacheAsync(dto))
.OnSuccessAsync(dto =>
_logger.LogInformation(
"Success: {Email}", dto.Email))
.OnErrorAsync((problem, status) =>
_logger.LogError(
"Error: {Title}", problem.Title))
.ToActionResult();
// Validation with RejectIf
return await GetOrderAsync(orderId)
.RejectIfAsync(
order => order.Total < 0,
() => ResultFactory.Common.BadRequest<Order>(
"OrderService",
"Invalid order total"))
.MapAsync(order => new OrderDto(order))
.ToActionResult();
// Error recovery with IfErrorAsync
return await CallExternalApiAsync(request)
.IfErrorAsync(
(problem, status) =>
status == HttpStatusCode.ServiceUnavailable,
async (problem, status) =>
await FallbackServiceAsync(request))
.ToActionResult();
// Combining multiple results
var userResult = await GetUserAsync(userId);
var orderResult = await GetOrderAsync(orderId);
return userResult.CombineWith(
orderResult,
(user, order) => new UserOrderDto(user, order))
.ToActionResult();
See Also
10 November 2025