C
C#2y ago
Thinker

How to handle results from a service [Answered]

I have the following service:
public interface ITodoService {
Task<IEnumerable<TodoList>> GetListsAsync();
Task<TodoList?> GetListFromIdAsync(Guid id);
Task<TodoItem?> GetItemFromIdAsync(Guid id);
Task<TodoItem?> AddItemToList(Guid listId, AddItemDto item);
}
public interface ITodoService {
Task<IEnumerable<TodoList>> GetListsAsync();
Task<TodoList?> GetListFromIdAsync(Guid id);
Task<TodoItem?> GetItemFromIdAsync(Guid id);
Task<TodoItem?> AddItemToList(Guid listId, AddItemDto item);
}
The nullable returns in some of the methods in this case indicate that the method may not find anything, except this feels a bit clunky as just a nullable return doesn't really communicate much intention and I end up having to in my API endpoints have specific cases for whether the item returned was nullable. In addition, more errors than just the item not being found could occur. I really don't wanna have to use a specific DU structure for every single method and hardcode what errors could occur as, well, I'd have to update it every time a new possible error could happen. I think I should use something like Remora.Results or some other functional result library, though I'd still like some feedback.
10 Replies
TheBoxyBear
TheBoxyBear2y ago
In asp mvc there's IActionResult that encapsulates the result or any errors if present Complete with implicit conversions so you don't have to create a result when returning
jcotton42
jcotton422y ago
That's not general purpose though Afaik
Thinker
Thinker2y ago
Yeah, I'm using currently Microsoft.AspNetCore.Http.IResult as the return from my endpoints, although I don't really wanna use this in my services as first and foremost the project doesn't even have a reference to any ASP.NET library, and secondly I feel like services shouldn't be bothered with endpoint-level concerns such as what status code to return.
TheBoxyBear
TheBoxyBear2y ago
Task itself also stores its error state
Thinker
Thinker2y ago
Not the kind of error state you can easily use as a "result" type state
jcotton42
jcotton422y ago
I'd use Remora
Thinker
Thinker2y ago
Now the only issue is the fact that Remora's type is also called IResult catsip
pox
pox2y ago
We use a Either class that either holds the item or and enum error code. Not a fan of result types that don't have hard typed errors Saw now that you don't want hardcoded errors
Thinker
Thinker2y ago
Eh, I'll figure something out
Accord
Accord2y ago
✅ This post has been marked as answered!