Defines base implementation for Result, with samples.

This commit is contained in:
BinaryAlley committed 2026-08-13 14:18:41 -07:00
1 parent c86893a0cf
commit 8fe90a4dde
20 files changed
+538 -7

No files matched your search

@@ -0,0 +1,10 @@
namespace Lumina.Domain.Common.Primitives;
/// <summary>
/// Error representing that the operation could not be completed due to a conflict with the current state.
/// </summary>
public record ConflictError(string Code, string Description) : Error
{
public override string Code { get; } = Code;
public override string Description { get; } = Description;
}
@@ -0,0 +1,6 @@
namespace Lumina.Domain.Common.Primitives;
/// <summary>
/// Represents a successful creation operation result.
/// </summary>
public readonly record struct Created;
@@ -0,0 +1,6 @@
namespace Lumina.Domain.Common.Primitives;
/// <summary>
/// Represents a successful deletion operation result.
/// </summary>
public readonly record struct Deleted;
@@ -0,0 +1,136 @@
namespace Lumina.Domain.Common.Primitives;
/// <summary>
/// Represents an error that can be implicitly converted to a Results.
/// </summary>
public abstract record Error
{
/// <summary>
/// Gets the error code that uniquely identifies this error type.
/// </summary>
public abstract string Code { get; }
/// <summary>
/// Gets the human-readable description of the error.
/// </summary>
public abstract string Description { get; }
/// <summary>
/// Returns a string representation of the error.
/// </summary>
/// <returns>A formatted string containing the error code and description.</returns>
public override string ToString()
{
return $"{Code}: {Description}";
}
/// <summary>
/// Creates a new NotFoundError with the specified description.
/// </summary>
/// <param name="description">The human-readable description of the error.</param>
/// <returns>A new NotFoundError instance with code "NotFound".</returns>
public static NotFoundError NotFound(string description)
{
return new("NotFound", description);
}
/// <summary>
/// Creates a new InvalidOperationError with the specified description.
/// </summary>
/// <param name="description">The human-readable description of the error.</param>
/// <returns>A new InvalidOperationError instance with code "InvalidOperation".</returns>
public static InvalidOperationError InvalidOperation(string description)
{
return new("InvalidOperation", description);
}
/// <summary>
/// Creates a new ForbiddenError with the specified description.
/// </summary>
/// <param name="description">The human-readable description of the error.</param>
/// <returns>A new ForbiddenError instance with code "Forbidden".</returns>
public static ForbiddenError Forbidden(string description)
{
return new("Forbidden", description);
}
/// <summary>
/// Creates a new FailureError with the specified description.
/// </summary>
/// <param name="description">The human-readable description of the error.</param>
/// <returns>A new FailureError instance with code "Failure".</returns>
public static FailureError Failure(string description)
{
return new("Failure", description);
}
/// <summary>
/// Creates a new ValidationError with the specified description.
/// </summary>
/// <param name="description">The human-readable description of the error.</param>
/// <returns>A new ValidationError instance with code "Validation".</returns>
public static ValidationError Validation(string description)
{
return new("Validation", description);
}
/// <summary>
/// Creates a new ConflictError with the specified description.
/// </summary>
/// <param name="description">The human-readable description of the error.</param>
/// <returns>A new ConflictError instance with code "Conflict".</returns>
public static ConflictError Conflict(string description)
{
return new("Conflict", description);
}
/// <summary>
/// Creates a new TimeoutError with the specified description.
/// </summary>
/// <param name="description">The human-readable description of the error.</param>
/// <returns>A new TimeoutError instance with code "Timeout".</returns>
public static TimeoutError Timeout(string description)
{
return new("Timeout", description);
}
/// <summary>
/// Creates a new UnauthorizedError with the specified description.
/// </summary>
/// <param name="description">The human-readable description of the error.</param>
/// <returns>A new UnauthorizedError instance with code "Unauthorized".</returns>
public static UnauthorizedError Unauthorized(string description)
{
return new("Unauthorized", description);
}
/// <summary>
/// Creates a new InternalError with the specified description.
/// </summary>
/// <param name="description">The human-readable description of the error.</param>
/// <returns>A new InternalError instance with code "Internal".</returns>
public static InternalError Internal(string description)
{
return new("Internal", description);
}
/// <summary>
/// Creates a new ResourceUnavailableError with the specified description.
/// </summary>
/// <param name="description">The human-readable description of the error.</param>
/// <returns>A new ResourceUnavailableError instance with code "ResourceUnavailable".</returns>
public static ResourceUnavailableError ResourceUnavailable(string description)
{
return new("ResourceUnavailable", description);
}
/// <summary>
/// Creates a new NotImplementedError with the specified description.
/// </summary>
/// <param name="description">The human-readable description of the error.</param>
/// <returns>A new NotImplementedError instance with code "NotImplemented".</returns>
public static NotImplementedError NotImplemented(string description)
{
return new("NotImplemented", description);
}
}
@@ -0,0 +1,10 @@
namespace Lumina.Domain.Common.Primitives;
/// <summary>
/// Error representing that some operation failing.
/// </summary>
public record FailureError(string Code, string Description) : Error
{
public override string Code { get; } = Code;
public override string Description { get; } = Description;
}
@@ -0,0 +1,10 @@
namespace Lumina.Domain.Common.Primitives;
/// <summary>
/// Error representing that the operation is not allowed due to insufficient permissions or restrictions.
/// </summary>
public record ForbiddenError(string Code, string Description) : Error
{
public override string Code { get; } = Code;
public override string Description { get; } = Description;
}
@@ -0,0 +1,10 @@
namespace Lumina.Domain.Common.Primitives;
/// <summary>
/// Error representing that an unexpected internal error occurred.
/// </summary>
public record InternalError(string Code, string Description) : Error
{
public override string Code { get; } = Code;
public override string Description { get; } = Description;
}
@@ -0,0 +1,10 @@
namespace Lumina.Domain.Common.Primitives;
/// <summary>
/// Error representing that the operation is invalid in the current state or context.
/// </summary>
public record InvalidOperationError(string Code, string Description) : Error
{
public override string Code { get; } = Code;
public override string Description { get; } = Description;
}
@@ -0,0 +1,10 @@
namespace Lumina.Domain.Common.Primitives;
/// <summary>
/// Error representing that the requested resource or entity was not found.
/// </summary>
public record NotFoundError(string Code, string Description) : Error
{
public override string Code { get; } = Code;
public override string Description { get; } = Description;
}
@@ -0,0 +1,10 @@
namespace Lumina.Domain.Common.Primitives;
/// <summary>
/// Error representing that the requested functionality is not implemented.
/// </summary>
public record NotImplementedError(string Code, string Description) : Error
{
public override string Code { get; } = Code;
public override string Description { get; } = Description;
}
@@ -0,0 +1,10 @@
namespace Lumina.Domain.Common.Primitives;
/// <summary>
/// Error representing that the required resource is currently unavailable.
/// </summary>
public record ResourceUnavailableError(string Code, string Description) : Error
{
public override string Code { get; } = Code;
public override string Description { get; } = Description;
}
@@ -0,0 +1,237 @@
namespace Lumina.Domain.Common.Primitives;
/// <summary>
/// Primitive struct for explicitly handling success and failure cases in a functional manner.
/// </summary>
/// <typeparam name="TValue">The type of the success value.</typeparam>
public readonly struct Result<TValue> : IEquatable<Result<TValue>>
{
private readonly TValue? _value;
private readonly List<Error>? _errors;
/// <summary>
/// Gets a value indicating whether this result represents a success.
/// </summary>
public bool IsSuccess { get; }
/// <summary>
/// Gets a value indicating whether this result represents a failure.
/// </summary>
public bool IsFailure => !IsSuccess;
/// <summary>
/// Gets the success value. Only valid when IsSuccess is true.
/// </summary>
public TValue Value => IsSuccess ? _value! : throw new InvalidOperationException("Cannot access Value of a failed result.");
/// <summary>
/// Gets the list of errors. Only valid when IsFailure is true.
/// </summary>
public List<Error> Errors => IsFailure
? _errors ?? []
: throw new InvalidOperationException("Cannot access Errors of a successful result.");
/// <summary>
/// Returns the first error, if present.
/// </summary>
public Error FirstError => Errors[0];
/// <summary>
/// Initializes a new instance of the <see cref="Result{TValue}"/> structure.
/// </summary>
/// <param name="value">The success value.</param>
/// <param name="errors">The list of errors.</param>
/// <param name="isSuccess">Whether this represents a success or failure.</param>
private Result(TValue? value, List<Error>? errors, bool isSuccess)
{
_value = value;
_errors = errors;
IsSuccess = isSuccess;
}
/// <summary>
/// Creates a successful result with the specified value.
/// </summary>
/// <param name="value">The success value.</param>
/// <returns>A successful result containing the specified value.</returns>
public static Result<TValue> Success(TValue value)
{
return new Result<TValue>(value, default, true);
}
/// <summary>
/// Creates a failed result with the specified errors.
/// </summary>
/// <param name="errors">The errors value.</param>
/// <returns>A failed result containing the specified error.</returns>
public static Result<TValue> Failure(List<Error> errors)
{
return new Result<TValue>(default, errors, false);
}
/// <summary>
/// Creates a failed result with the specified errors.
/// </summary>
/// <param name="errors">The errors value.</param>
/// <returns>A failed result containing the specified error.</returns>
public static Result<TValue> Failure(params Error[] errors)
{
return new(default, [.. errors], false);
}
/// <summary>
/// Custom implementation operator for converting <paramref name="value"/> to a <see cref="Result{TValue}"/>.
/// </summary>
/// <param name="value">The value to be converted.</param>
public static implicit operator Result<TValue>(TValue value)
{
return Success(value);
}
/// <summary>
/// Custom implementation operator for converting <paramref name="error"/> to a failed <see cref="Result{TValue}"/>.
/// </summary>
/// <param name="error">The error to be converted.</param>
public static implicit operator Result<TValue>(Error error)
{
return Failure(error);
}
/// <summary>
/// Custom implementation operator for converting <paramref name="errors"/> to a failed <see cref="Result{TValue}"/>.
/// </summary>
/// <param name="errors">The errors to be converted.</param>
public static implicit operator Result<TValue>(List<Error> errors)
{
return Failure(errors);
}
/// <summary>
/// Maps the success value to a new type using the provided function.
/// </summary>
/// <typeparam name="TNewValue">The type of the new success value.</typeparam>
/// <param name="mapper">The function to transform the success value.</param>
/// <returns>A new result with the transformed value, or the original errors.</returns>
public Result<TNewValue> Map<TNewValue>(Func<TValue, TNewValue> mapper)
{
return IsSuccess
? Result<TNewValue>.Success(mapper(Value))
: Result<TNewValue>.Failure(Errors);
}
/// <summary>
/// Chains another operation that returns a Result, allowing for monadic composition.
/// </summary>
/// <typeparam name="TNewValue">The type of the new success value.</typeparam>
/// <param name="binder">The function that returns a new Results.</param>
/// <returns>The result of the chained operation, or the original error.</returns>
public Result<TNewValue> Bind<TNewValue>(Func<TValue, Result<TNewValue>> binder)
{
return IsSuccess ? binder(Value) : Result<TNewValue>.Failure(Errors);
}
/// <summary>
/// Executes an action if the result is successful, otherwise does nothing.
/// </summary>
/// <param name="action">The action to execute on success.</param>
/// <returns>The original result for chaining.</returns>
public Result<TValue> OnSuccess(Action<TValue> action)
{
if (IsSuccess)
action(Value);
return this;
}
/// <summary>
/// Executes an action if the result is a failure, otherwise does nothing.
/// </summary>
/// <param name="action">The action to execute on failure.</param>
/// <returns>The original result for chaining.</returns>
public Result<TValue> OnFailure(Action<IReadOnlyList<Error>> action)
{
if (IsFailure)
action(Errors);
return this;
}
/// <summary>
/// Matches the result and executes the appropriate function.
/// </summary>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="onSuccess">Function to execute on success.</param>
/// <param name="onFailure">Function to execute on failure.</param>
/// <returns>The result of the executed function.</returns>
public TResult Match<TResult>(Func<TValue, TResult> onSuccess, Func<List<Error>, TResult> onFailure)
{
return IsSuccess ? onSuccess(Value) : onFailure(Errors);
}
/// <summary>
/// Determines whether the specified Result is equal to the current Results.
/// </summary>
/// <param name="other">The Result to compare with the current Results.</param>
/// <returns>true if the specified Result is equal to the current Result; otherwise, false.</returns>
public bool Equals(Result<TValue> other)
{
if (IsSuccess != other.IsSuccess)
return false;
return IsSuccess
? EqualityComparer<TValue>.Default.Equals(Value, other.Value)
: Errors.SequenceEqual(other.Errors);
}
/// <summary>
/// Determines whether the specified object is equal to the current Results.
/// </summary>
/// <param name="obj">The object to compare with the current Results.</param>
/// <returns>true if the specified object is equal to the current Result; otherwise, false.</returns>
public override bool Equals(object? obj)
{
return obj is Result<TValue> other && Equals(other);
}
/// <summary>
/// Determines whether two specified Result instances are equal.
/// </summary>
/// <param name="left">The first Result to compare.</param>
/// <param name="right">The second Result to compare.</param>
/// <returns>true if the two Result instances are equal; otherwise, false.</returns>
public static bool operator ==(Result<TValue> left, Result<TValue> right)
{
return left.Equals(right);
}
/// <summary>
/// Determines whether two specified Result instances are not equal.
/// </summary>
/// <param name="left">The first Result to compare.</param>
/// <param name="right">The second Result to compare.</param>
/// <returns>true if the two Result instances are not equal; otherwise, false.</returns>
public static bool operator !=(Result<TValue> left, Result<TValue> right)
{
return !(left == right);
}
/// <summary>
/// Returns the hash code for this Results.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return IsSuccess
? HashCode.Combine(IsSuccess, Value)
: HashCode.Combine(IsSuccess, Errors);
}
/// <summary>
/// Customized ToString() method.
/// </summary>
/// <returns>Custom string value showing relevant data for current result.</returns>
public override string ToString()
{
return IsSuccess
? $"Success: {Value?.ToString()}"
: $"Failure: [{string.Join(", ", Errors.Select(error => error.ToString()))}]";
}
}
@@ -0,0 +1,27 @@
namespace Lumina.Domain.Common.Primitives;
/// <summary>
/// Provides predefined success results for operations that don't return meaningful data.
/// </summary>
public static class Results
{
/// <summary>
/// Represents a successful operation.
/// </summary>
public static Success Success { get; } = new();
/// <summary>
/// Represents a successful creation operation.
/// </summary>
public static Created Created { get; } = new();
/// <summary>
/// Represents a successful update operation.
/// </summary>
public static Updated Updated { get; } = new();
/// <summary>
/// Represents a successful deletion operation.
/// </summary>
public static Deleted Deleted { get; } = new();
}
@@ -0,0 +1,6 @@
namespace Lumina.Domain.Common.Primitives;
/// <summary>
/// Represents a successful operation result.
/// </summary>
public readonly record struct Success;
@@ -0,0 +1,10 @@
namespace Lumina.Domain.Common.Primitives;
/// <summary>
/// Error representing that the operation timed out before completion.
/// </summary>
public record TimeoutError(string Code, string Description) : Error
{
public override string Code { get; } = Code;
public override string Description { get; } = Description;
}
@@ -0,0 +1,10 @@
namespace Lumina.Domain.Common.Primitives;
/// <summary>
/// Error representing that authentication is required or has failed.
/// </summary>
public record UnauthorizedError(string Code, string Description) : Error
{
public override string Code { get; } = Code;
public override string Description { get; } = Description;
}
@@ -0,0 +1,6 @@
namespace Lumina.Domain.Common.Primitives;
/// <summary>
/// Represents a successful update operation result.
/// </summary>
public readonly record struct Updated;
@@ -0,0 +1,10 @@
namespace Lumina.Domain.Common.Primitives;
/// <summary>
/// Error representing that the input or data failed validation rules.
/// </summary>
public record ValidationError(string Code, string Description) : Error
{
public override string Code { get; } = Code;
public override string Description { get; } = Description;
}
@@ -1,5 +1,4 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.Common.Models.Core;
using Lumina.Domain.Common.Primitives;
@@ -233,9 +232,9 @@ public sealed class Book : AggregateRoot<BookId>
/// <param name="contributors">The list of objects representing the unique identifiers of the media contributors of the book.</param>
/// <param name="ratings">The list of ratings for the book.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="Book"/>, or an error message.
/// An <see cref="Result{TValue}"/> containing either a successfully created <see cref="Book"/>, or an error message.
/// </returns>
public static ErrorOr<Book> Create(
public static Result<Book> Create(
LibraryId libraryId,
string path,
WrittenContentMetadata metadata,
@@ -309,9 +308,9 @@ public sealed class Book : AggregateRoot<BookId>
/// <param name="contributors">The list of objects representing the unique identifiers of the media contributors of the book.</param>
/// <param name="ratings">The list of ratings for the book.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="Book"/>, or an error message.
/// An <see cref="Result{TValue}"/> containing either a successfully created <see cref="Book"/>, or an error message.
/// </returns>
public static ErrorOr<Book> Create(
public static Result<Book> Create(
BookId id,
LibraryId libraryId,
string path,
@@ -45,10 +45,8 @@ public class PluginsController : Controller
// load the settings of the loaded plugins, so that the settings forms can be rendered on the server
Dictionary<Guid, PluginSettingsModel> settingsByPluginId = [];
foreach (PluginModel plugin in plugins)
{
if (plugin.LoadStatus == PluginLoadStatus.Loaded)
settingsByPluginId[plugin.Id] = await _apiHttpClient.GetAsync<PluginSettingsModel>($"plugins/{plugin.Id}/settings", cancellationToken).ConfigureAwait(false);
}
ViewData["pluginSettings"] = settingsByPluginId;
return View(plugins);