DeepCode.Return
1.1.1
There is a newer version of this package available.
See the version list below for details.
See the version list below for details.
dotnet add package DeepCode.Return --version 1.1.1
NuGet\Install-Package DeepCode.Return -Version 1.1.1
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="DeepCode.Return" Version="1.1.1" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add DeepCode.Return --version 1.1.1
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: DeepCode.Return, 1.1.1"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install DeepCode.Return as a Cake Addin #addin nuget:?package=DeepCode.Return&version=1.1.1 // Install DeepCode.Return as a Cake Tool #tool nuget:?package=DeepCode.Return&version=1.1.1
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
Simplify error handling and improve code readability with the Result Pattern
Get Started
Install nuget package using .Net CLI
or nuget using Nuget package manager GUI by searching DeepCode.Return
dotnet add package DeepCode.Return --version 1.0.1
How To Use
Define method return type with Return struct with TResult type parameter
TResult is type of the return
namespace Invoicing.Application.Orders.Commands.CreateOrderCommand;
internal class CreateOrderCommandHandler : IRequestHandler<CreateOrderCommand, Return<Order>>
{
public async Task<Return<Order>> Handle(CreateOrderCommand request, CancellationToken cancellationToken)
{
Order order;
//order creation logic
return order;
}
}
for non async methods
public Return<Order> CreateOrder(CreateOrder request, CancellationToken cancellationToken)
{
Order order;
//order creation logic
return order;
}
Return struct can be used when there's no return value but to notify if function was success or not
public Return SendEmail()
{
return Return.Success();
}
How to extract if state is success
public void Main()
{
Return<Order> orderCreateResult = CreateOrder(request, cancellationToken);
if(orderCreateResult.IsFailure)
{
// Failure code goes here
}
Order order = orderCreateResult.Value;
// success path here
}
Error Handling
Notify caller error with in built error types
Handle Conflicts,
public Return<Order> CreateOrder(double totalAmount)
{
// logic to apply the discount if total amount is > 100
// Inventory says out of stock due to high demand
if (!inventoryManagement.AreEnoughStokesAvailable())
{
return Fault.Conflict("Not enough stockes in inventory.");
//or
return Return<Order>.Failure(Conflict.Create("Not enough stockes in inventory."));
}
}
Other in-built error type available
// all these take one string message arg and optinal description arg
return Fault.NotFound();
return Fault.InternalError();
return Fault.ReturnError();
Handle Errors from caller method
public Return Main()
{
Return<Order> orderCreateResult = CreateOrder(100);
if (orderCreateResult.IsFailure)
{
// First error or only error of the list.
Fault error = orderCreateResult.Error;
// Read all errors returned.
IReadOnlyList<Fault> errors = orderCreateResult.Errors;
// Error logic goes here
}
if (orderCreateResult.IsFailure)
{
// Pass errors to call stack
return orderCreateResult.Errors.ToList();
}
}
Define custom error types
Need to be inherited from Fault record
public record OrderCreationErrors : Fault
{
public OrderCreationErrors(string message, string? description = null) : base(message, description) { }
public static OrderCreationErrors InvalidCustomerIdForOrderCreation =>
new OrderCreationErrors("Could not find matching customer to the given customerId.");
public static OrderCreationErrors CustomerBlacklisted =>
new OrderCreationErrors("Customer with the given customerId has been blacklisted.");
}
Using Match
Match method can be used to trigger actions when some return is success or failure.
Trigger actions with no return type.
Return<Order> orderCreateResult = CreateOrder(100);
orderCreateResult.Match(
onSuccess: (value) => _logger.Info($"{value.Id} Order created successfully."),
onFailure: (errors) => _logger.Error("Failed to create order.")
);
//Match first error of errors if failure.
orderCreateResult.MatchFirst(
onSuccess: (value) => _logger.Info($"{value.Id} Order created successfully."),
onFailure: (error) => _logger.Error("Failed to create order.")
);
orderCreateResult.MatchAsync(
onSuccess: async (value) =>
{
// Simulating async process
await Task.Delay(100);
_logger.Info($"{value.Id} Order created successfully.");
},
onFailure: async (errors) =>
{
// Simulating async process
await Task.Delay(100);
_logger.Error("Failed to create order.");
});
Match using TNextValue type, has return after match
Return<Order> orderCreateResult = Return<Order>.Success(new Order());
Response<Order> response = orderCreateResult.Match<Response<Order>>(
onSuccess:(order) => new Response<Order>() { Data = order },
onFailure:(errors) => new Response<Order>() { Error = new { Error = errors.ToList() } });
//gets first error of the list as the arg when failure.
Response<Order> response = orderCreateResult.MatchFirst<Response<Order>>(
onSuccess:(order) => new Response<Order>() { Data = order },
onFailure:(error) => new Response<Order>() { Error = new { Error = errors.ToList() } });
Response<Order> response = orderCreateResult.MatchAsync<Response<Order>>(
onSuccess: async (order) => {},
onFailure: async (errors) => {});
//gets first error of the list as the arg when failure.
Response<Order> response = orderCreateResult.MatchFirstAsync<Response<Order>>(
onSuccess: async (order) => {},
onFailure: async (error) => {});
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. |
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
-
net8.0
- No dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.