C
C#8mo ago
johannesa

✅ Hello!

I have a service class who talks to an repo that talks to the database. Im so confused to where to implement error-handling. For example if i try to add something to the database and something goes wrong, where and how should i handle this?
8 Replies
kurumi
kurumi8mo ago
if this error related to adding item, it should throw exception in your repository. So you need to catch it from calling service (or re-throw if you need to take some data in exception). If the data corrupted and you can check it before an actual request, then validation is what you need. Validation should be is early as could be. Also, I personally recommend to return Problem wrapper in your repository. So in calling service you just need to check:
var someValueFromDatabase = await _repository.GetSomeValueAsync();

if (someValueFromDatabase.Success)
{
// it is OK, no errors
}
else
{
var problemDetails = someValueFromDatabase.Problems;
}
var someValueFromDatabase = await _repository.GetSomeValueAsync();

if (someValueFromDatabase.Success)
{
// it is OK, no errors
}
else
{
var problemDetails = someValueFromDatabase.Problems;
}
this approach can be done with many libraries or you create your own
johannesa
johannesaOP8mo ago
OKay thank you! Is this a good approach? This is the add method in the repo public async Task AddAsync(Product product) { try { await storeContext.AddAsync(product); await storeContext.SaveChangesAsync(); } catch (Exception ex) { Console.WriteLine(@$"Ett fel inträffade, vid försök av att lägga till en entity i databasen. {ex.Message}"); } } Right now its just writing the that an error occured to the console. But i read something about an logger i could use later
kurumi
kurumi8mo ago
is it EF Core? caz it looks like you are creating a repository for DbSet which is already generic repository
johannesa
johannesaOP8mo ago
Yes its entityframework core, I will be using SqlLite for now but later i might use server instead. But okay so the DBset alrdy acts as a repo, so the service talks directly to Ef then
kurumi
kurumi8mo ago
yes, you don't need to create new one, just inject your DbContext and use your DbSets
johannesa
johannesaOP8mo ago
alright thanks alot for your help 🙂
kurumi
kurumi8mo ago
$close
MODiX
MODiX8mo ago
Use the /close command to mark a forum thread as answered
Want results from more Discord servers?
Add your server