-
-
Save dimitris-papadimitriou-chr/cf695424c73cd61fc93cbcca91903a0f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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