Last active
February 3, 2025 20:36
-
-
Save pedroinfo/d3b07c511bfd24b5ca54ef484916020b 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
public class Result<T> | |
{ | |
public T Value { get; } | |
public string Error { get; } | |
public bool IsSuccess => Error == null; | |
private Result(T value, string error) | |
{ | |
Value = value; | |
Error = error; | |
} | |
public static Result<T> Success(T value) => new(value, null); | |
public static Result<T> Failure(string error) => new(default, error); | |
} | |
[ApiController] | |
[Route("api/users")] | |
public class UserController : ControllerBase | |
{ | |
private static readonly Dictionary<int, string> Users = new() | |
{ | |
{ 1, "Alice" }, | |
{ 2, "Bob" } | |
}; | |
[HttpGet("{id}")] | |
public ActionResult<Result<string>> GetUser(int id) | |
{ | |
var result = GetUserById(id); | |
if (!result.IsSuccess) | |
{ | |
return BadRequest(result); | |
} | |
return Ok(result); | |
} | |
private Result<string> GetUserById(int id) | |
{ | |
if (Users.TryGetValue(id, out var user)) | |
{ | |
return Result<string>.Success(user); | |
} | |
return Result<string>.Failure("User not found."); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment