C
C#2mo ago
Alex

Service layer exception or bool/error object

Should I throw an exception and catch it in global handler or try catch it in method and return bool/error object if I implement method on service layer?
3 Replies
Merhex
Merhex2mo ago
In my experience it is better to return a response object containing information about the request from the service layer, not simply a boolean as it can be ambiguous to its meaning. Per example, say something happened during the request, you return a response object with an error message inside. How this response object looks like is up to you, but great places to start are discriminated unions, or a library like ErrorOr
kurumi
kurumi2mo ago
TL;DR: 1. never do booleans (it is not flexible enough) 2. use exceptions if you don't wanna deal with multiple Result checking in each service 3. use Result if you want to improve performance, but need to wrap each service with it and do many checks 3.1. if you choose Result, then don't mix failed Result with a real Exception (for ex: database connection was expired) 3.2 if you choose Result, look at some already made libraries by community. My suggestion is FluentResult There are 2 common ways for this: 1) you can throw exception and catch them 2) you can use Result<T> model, which represents the result of some operation and then perform failure checking First case is simple, but it may be not the best performance. It's easy to catch exceptions in top level execution code In second scenario all calling services which working with your Result<T> should also check if result is success or failed and in case it's failed wrap in another Result<T2> with all needed information. I never suggest anyone to use booleans because they are not flexible enough if you need some details on what's wrong. Depends on what you need you should choose one of these approaches. And also don't mix failed result with a real exception. For example: 1) failed result if you can not create another user with already existed login 2) exception if you can not create a new field on your database because connection was expired for some reason If you choose Result<T> then it's better to use some libraries, because Result type is pretty routine and many people already implemented this on theirs libs.
GitHub
GitHub - altmann/FluentResults: A generalised Result object impleme...
A generalised Result object implementation for .NET/C# - altmann/FluentResults
Alex
AlexOP2mo ago
thank you for the answer
Want results from more Discord servers?
Add your server