Skip to content

sqlviewer / result pattern. #22

@alexeysp11

Description

@alexeysp11

Description

You can use some existing library for implementing the Result Pattern in your code: for example, FluentResults.
You can also try using your own implementation:

public interface IOperationResult<out T>
{
    bool IsSuccess { get; }
    T? Value { get; }
    string? ErrorMessage { get; }
    Exception? Exception { get; }
}

public class OperationResult<T> : IOperationResult<T>
{
    public bool IsSuccess { get; }
    public T? Value { get; }
    public string? ErrorMessage { get; }
    public Exception? Exception { get; }

    protected OperationResult(bool isSuccess, T? value, string? errorMessage, Exception? ex = null)
    {
        IsSuccess = isSuccess;
        Value = value;
        ErrorMessage = errorMessage;
        Exception = ex;
    }

    public static OperationResult<T> Success(T value) 
        => new(true, value, null);

    public static OperationResult<T> Failure(string message, Exception? ex = null) 
        => new(false, default, message, ex);
}

public class OperationResult : OperationResult<object>
{
    private OperationResult(bool isSuccess, string? errorMessage) 
        : base(isSuccess, null, errorMessage) { }

    public static OperationResult Success() => new(true, null);
    public static new OperationResult Failure(string message) => new(false, message);
}

public async Task<IOperationResult<List<dynamic>>> QueryAsync(string query)
{
    try 
    {
        if (string.IsNullOrWhiteSpace(query))
            return OperationResult<List<dynamic>>.Failure("Query could not be empty");

        var data = await _db.ExecuteAsync(query);
        return OperationResult<List<dynamic>>.Success(data);
    }
    catch (Exception ex)
    {
        return OperationResult<List<dynamic>>.Failure("Database error", ex);
    }
}

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions