RGamaFelix.ServiceResponse
3.1.0
dotnet add package RGamaFelix.ServiceResponse --version 3.1.0
NuGet\Install-Package RGamaFelix.ServiceResponse -Version 3.1.0
<PackageReference Include="RGamaFelix.ServiceResponse" Version="3.1.0" />
<PackageVersion Include="RGamaFelix.ServiceResponse" Version="3.1.0" />
<PackageReference Include="RGamaFelix.ServiceResponse" />
paket add RGamaFelix.ServiceResponse --version 3.1.0
#r "nuget: RGamaFelix.ServiceResponse, 3.1.0"
#:package RGamaFelix.ServiceResponse@3.1.0
#addin nuget:?package=RGamaFelix.ServiceResponse&version=3.1.0
#tool nuget:?package=RGamaFelix.ServiceResponse&version=3.1.0
RGamaFelix.ServiceResponse
A robust .NET library for handling service operation results with structured error handling and type safety.
Overview
RGamaFelix.ServiceResponse provides a consistent way to handle the results of service operations, whether they succeed
or fail. It encapsulates data, errors, exceptions, and result status codes in a type-safe manner, making it easier to
build reliable applications with proper error handling.
Features
- ✅ Type-safe result handling with generic support
- ✅ Multiple error collection with structured error messages
- ✅ Exception wrapping for unexpected errors
- ✅ Result type codes for categorizing different outcomes
- ✅ Implicit conversions for seamless integration
- ✅ Rich debugging support with comprehensive
ToString()implementation - ✅ Interface-based design for better testability and flexibility
Installation
dotnet add package RGamaFelix.ServiceResponse
Quick Start
Basic Usage
using RGamaFelix.ServiceResponse;
// Success case
var successResult = ServiceResultOf.Success("Hello World", ResultTypeCode.Success);
if (successResult.IsSuccess)
{
Console.WriteLine(successResult.Data); // "Hello World"
}
// Failure case with single error
var failureResult = ServiceResultOf.Fail("Something went wrong", ResultTypeCode.ValidationError);
if (!failureResult.IsSuccess)
{
Console.WriteLine(failureResult.ToErrorString());
}
// Failure case with multiple errors
var multipleErrors = new[] { "Error 1", "Error 2", "Error 3" };
var multiErrorResult = ServiceResultOf.Fail(multipleErrors, ResultTypeCode.ValidationError);
Exception Handling
try
{
// Some operation that might throw
throw new InvalidOperationException("Something unexpected happened");
}
catch (Exception ex)
{
var result = ServiceResultOf.Fail(ex); Console.WriteLine( "Exception: {result.Exception?.Message}"); Console.WriteLine("Errors: {result.ToErrorString()}");
}
Implicit Conversions
The library supports implicit conversions for seamless integration:
// Convert to data type
ServiceResultOfresult = ServiceResultOf .Success("data", ResultTypeCode.Success);
string data = result; // Implicit conversion to string
// Convert to exception
ServiceResultOferrorResult = ServiceResultOf .Fail(new Exception("error")); Exception?exception = errorResult; // Implicit conversion to Exception
API Reference
IServiceResultOf<T>
The main interface that defines the contract for service results.
Properties
T? Data- The data returned from a successful operationIReadOnlyCollection<string> Errors- Collection of error messagesException? Exception- The exception that occurred (if any)bool IsSuccess- Indicates if the operation was successfulResultTypeCode ResultType- The type of result (success or error category)
Methods
string ToErrorString()- Formats all errors into a single string
ServiceResultOf<T>
The concrete implementation of IServiceResultOf<T>.
Static Factory Methods
Success Methods:
Success(T data, ResultTypeCode resultType)- Creates a successful result
Failure Methods:
Fail(string error, ResultTypeCode resultType)- Creates a failed result with single errorFail(IEnumerable<string> errors, ResultTypeCode resultType)- Creates a failed result with multiple errorsFail(Exception exception)- Creates a failed result from an exception
Best Practices
1. Use Appropriate Result Type Codes
// For validation errors
var result = ServiceResultOf.Fail("Invalid email format", ResultTypeCode.ValidationError);
// For business logic violations
var result = ServiceResultOf.Fail("Insufficient inventory", ResultTypeCode.BusinessRuleViolation);
// For successful operations
var result = ServiceResultOf.Success(user, ResultTypeCode.Success);
2. Handle Both Success and Failure Cases
var result = userService.GetUser(userId);
if (result.IsSuccess)
{
ProcessUser(result.Data);
}
else
{
LogErrors(result.Errors);
if (result.Exception != null)
{
LogException(result.Exception);
}
}
3. Use in Service Layer
public class UserService
{
public IServiceResultOfCreateUser(CreateUserRequest request)
{
// Validation
if (string.IsNullOrEmpty(request.Email))
{
return ServiceResultOf .Fail("Email is required", ResultTypeCode.ValidationError);
}
try
{
var user = new User(request.Email, request.Name);
_repository.Add(user);
return ServiceResultOf<User>.Success(user, ResultTypeCode.Created);
}
catch (Exception ex)
{
return ServiceResultOf<User>.Fail(ex);
}
}
}
Advanced Scenarios
Working with Multiple Errors
var errors = new List();
if (string.IsNullOrEmpty(request.Name)) errors.Add("Name is required");
if (string.IsNullOrEmpty(request.Email)) errors.Add("Email is required");
if (!IsValidEmail(request.Email)) errors.Add("Email format is invalid");
if (errors.Any())
{
return ServiceResultOf.Fail(errors, ResultTypeCode.ValidationError);
}
Chaining Operations
public IServiceResultOfProcessData(int id)
{
var fetchResult = _dataService.FetchData(id);
if (!fetchResult.IsSuccess)
{
return ServiceResultOf.Fail(fetchResult.Errors, fetchResult.ResultType);
}
try
{
var processed = ProcessRawData(fetchResult.Data);
return ServiceResultOf<ProcessedData>.Success(processed, ResultTypeCode.Success);
}
catch (Exception ex)
{
return ServiceResultOf<ProcessedData>.Fail(ex);
}
}
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Support
If you encounter any issues or have questions, please file an issue on the GitHub repository.
| 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. net9.0 is compatible. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- No dependencies.
-
net8.0
- No dependencies.
-
net9.0
- No dependencies.
NuGet packages (2)
Showing the top 2 NuGet packages that depend on RGamaFelix.ServiceResponse:
| Package | Downloads |
|---|---|
|
RGamaFelix.ServiceResponse.RestResponse
ASP.NET Core integration for RGamaFelix.ServiceResponse. Maps IServiceResultOf<T> to IActionResult with automatic HTTP status code selection and configurable error detail level. |
|
|
RGamaFelix.ServiceResponse.FluentValidation
FluentValidation integration for RGamaFelix.ServiceResponse. Converts ValidationResult to IServiceResultOf<T> with InvalidData result code. |
GitHub repositories
This package is not used by any popular GitHub repositories.