Skip to content

Instantly share code, notes, and snippets.

@dimitris-papadimitriou-chr
Created February 21, 2021 19:38
Show Gist options
  • Save dimitris-papadimitriou-chr/cf695424c73cd61fc93cbcca91903a0f to your computer and use it in GitHub Desktop.
Save dimitris-papadimitriou-chr/cf695424c73cd61fc93cbcca91903a0f to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using LanguageExt;
namespace PracticalCSharp.Either.Monad.Exception
{
public static partial class FunctionalExtensions
{
public static T GetOrThrowException<T>(this Either<string, T> @either)
=> @either.Match(
Right: (T value) => value,
Left: (string error) => throw new System.Exception(error)
);
}
public class Client
{
public int Id { get; set; }
public string Name { get; set; }
public int EmployeeId { get; set; }
}
public class MockClientRepository
{
List<Client> clients = new List<Client>{
new Client{Id=1, Name="Jim", EmployeeId=1},
new Client{Id=2, Name="John", EmployeeId=4}
};
public Either<string, Client> GetById(int id)
{
Option<Client> t = clients.SingleOrDefault(x => x.Id == id);
return t.ToEither("no Client Found");
}
}
public class Controller
{
MockClientRepository clients = new MockClientRepository();
public string GetAssignedEmployeeNameById(int clientId) =>
clients
.GetById(clientId)
.Map(client => client.Name)
.GetOrThrowException();
}
public class Demo
{
public void Run()
{
try
{
var assignedEmployeeName = new Controller().GetAssignedEmployeeNameById(1);
assignedEmployeeName = new Controller().GetAssignedEmployeeNameById(3); //throws exception
}
catch (System.Exception e)
{
//throw;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment