Giter VIP home page Giter VIP logo

bettererrors's Introduction

BetterErrors

A very simple discriminated union of success or error

dotnet add package BetterErrors

Getting Started

Result<User> GetUser(Guid id = default)
{
    if (id == default)
    {
        return new Error("Id is required");
    }

    return new User(Name: "Amichai");
}
GetUser(...).Switch(
    user => Console.WriteLine(user),
    error => Console.WriteLine(error.Message));

A more practical example

public Result<User> CreateUser(string name, string email)
{
    List<FieldErrorInfo> fieldErrors = new();

    if (name.Length < 2)
    {
        fieldErrors.Add(new("Name", "Name is too short"));
    }

    if (name.Length > 100)
    {
        fieldErrors.Add(new("Name", "Name is too long"));
    }

    if (!validateEmail(email))
    {
        fieldErrors.Add(new("Email", "Email is invalid"));
    }

    if (fieldErrors.Count > 0)
    {
        return new ValidationError("Provided data is not valid", fieldErrors);
    }
    ......User creation logic
}
public Task<ErrorOr<User>> AddUserAsync(string name, string email)
{
    return CreateUser(name, email).Map<User>(async user => // Note: You have to pass the generic type parameter explicitly for map method
    {
        await _dbContext.AddAsync(user);
        return user;
    });
}
[HttpGet("/users/create")]
public async Task<IActionResult> CreateUser(CreateUserRequest req)
{
    Result<User> userResult = await _repo.AddUserAsync(req.Name, req.Email);

    return userResult.Match(
        user => Ok(user),
        error => MapToActionResult(error));
}

public IActionResult MapToActionResult(IError err) => err switch
{
    ValidationError vErr => BadRequest(new { Errors = vErr.ErrorInfos, Message = vErr.Message }),
    NotFoundError nErr => NotFound(new { Message = nErr.Message }),
    _ => Problem()
}

Usage

Creating Result<T>

There are implicit converters from T, Error, List<Error>, Error[] to Result<T>

Creating Result<T> from IError

IError is an interface and C# doesn't support implicit conversion from/to interface. So you have to call a Method ToResult on IError

IError err = ...;
Result<T> result = Result.FromErr<T>(err);
// or
Result<T> result = err.ToResult<T>();

Checking if the Result<T> is an error

if (result.IsFailure)
{
    // result is an error
}

Accessing the Result<T> result

Accessing the Value

Result<int> result = Result.From(5);

var value = result.Value;

Accessing the Error

Result<int> result = new NotFoundError(...);

IError value = result.Error;

Performing actions based on the Result<T> result

Match

string foo = result.Match(
    value => value,
    error => $"err: {error.Message}");

Switch

Actions that don't return a value on the value or list of errors

result.Switch(
    value => Console.WriteLine(value),
    error => Console.WriteLine($"err: {error.Message}"));

Map

Map method takes a delegate which will transform success result to Result<TMap>. The delegate will only be called if Result<T> contains a success result. If Result<T> is contains a failure result then a Result<TMap> will be constructed with the errors inside Result<T>

Result<string> userNameResult = userResult.Map<string>(user => user.Username);

Note: Pass the generic type parameter explicitly for Map method

You can even return error in Map method

Result<string> userNameResult = userResult.Map<string>(user => 
{
    if(user.HasName)
    {
        return user.Username;
    }
    return new Error("user doesn't have username");
});

Result without a type

Result DeleteUser(Guid id)
{
    var user = await _userRepository.GetByIdAsync(id);
    if (user is null)
    {
        return new NotFoundError("User not found");
    }

    await _userRepository.DeleteAsync(user);
    return Result.Success;
}

Error Types

Built-in Error Types

  • Error
  • ValidationError,
  • AggregateError,
  • NotFoundError

Custom error

You can create your own error type. You can either implement the IError interface or inherit the Error record.

Benefit of implementing IError interface

You get more control on your type. But you can't implicitly convert it to Result

Benefit of inheriting Error record

Can be converted Implicitly to Result

Examples

FileNotFoundError notFoundErr = new("file.txt");
Result<T> result = Result.FromErr<T>(notFoundErr); // Ok
Result<T> result = notFoundErr.ToResult<T>(); // Ok
Result<T> result = notFoundErr; // Error

public class FileNotFoundError : IError
{
    public FileNotFoundError(string fileName)
    {
        FileName = fileName;
    }

    public string FileName { get; }

    public string Message => $"{FileName} was not found";

    public string Code => nameof(FileNotFoundError);
}
FileNotFoundError notFoundErr = new("file.txt");
Result<T> result = Result.FromErr<T>(notFoundErr); // Ok
Result<T> result = notFoundErr.ToResult<T>(); // Ok
Result<T> result = notFoundErr; // Ok too

public record FileNotFoundError(string FileName) : Error($"{FileName} was not found", nameof(FileNotFoundError));

Suggestions and Changes

Any suggestion on improving this project will be helpful

Credits

  • ErrorOr - A simple, fluent discriminated union of an error or a result. BetterErrors package is directly inspired from ErrorOr package with the benefits of error customization

bettererrors's People

Contributors

ziaulhasanhamim avatar

Stargazers

 avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.