Skip to main content

RA.Utilities.Core

NuGet version Codecov GitHub license NuGet Downloads

RA.Utilities.Core is a lightweight .NET library designed to enhance error handling by providing a functional Result type. It helps you write cleaner, more predictable, and more robust code by avoiding exceptions for expected operational failures. This approach allows for a clear and explicit representation of success or failure, making your application's control flow easier to follow and maintain.

๐ŸŽฏ Purposeโ€‹

In many applications, exceptions are used for both unexpected system faults (e.g., NullReferenceException) and predictable business-level failures (e.g., "user not found"). This can lead to complex try-catch blocks and makes it difficult to distinguish between recoverable errors and true exceptions.

The Result type solves this by providing a wrapper that explicitly represents one of two outcomes:

  • Success: The operation completed successfully, and may contain a value.
  • Failure: The operation failed, and contains an Exception detailing the error.

This pattern encourages you to handle failures as part of your normal code flow, leading to more readable and resilient applications.

๐Ÿ› ๏ธ Installationโ€‹

You can install the package via the .NET CLI:

dotnet add package RA.Utilities.Core

Or through the NuGet Package Manager console:

Install-Package RA.Utilities.Core

Or through the NuGet Package Manager in Visual Studio.


When to use Results Pattern and when to use Exceptionsโ€‹

LayerUse Results PatternUse Exceptions
โœ… Application Layerโœ… YesโŒ Avoid
โœ… Domain Layerโœ… YesโŒ Avoid
๐ŸŒ InfrastructureโŒ Rarelyโœ… Yes
๐ŸŒ External APIsโŒโœ… Required
๐Ÿงช Testsโœ… Preferredโœ… Avoid
SituationUse
Input validation failedโœ… Result pattern
Business rule not satisfiedโœ… Result pattern
DB connection failedโš ๏ธ Exception
File not found (unexpected)โš ๏ธ Exception
You want to chain logic stepsโœ… Result pattern
You need a stack trace.โš ๏ธ Exception

The Result Typeโ€‹

  • Result: Represents the outcome of an operation that does not return a value. It can be either a success or a failure.
  • Result<T>: Represents the outcome of an operation that returns a value of type T. It can be a success holding a T value, or a failure holding an Exception.

Factory Methodsโ€‹

  • Result.Success(): Creates a success result.
  • Result.Failure(Exception exception): Creates a failure result.