✅ 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
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:
this approach can be done with many libraries or you create your ownOKay 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 lateris it EF Core?
caz it looks like you are creating a repository for
DbSet
which is already generic repositoryYes 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
yes, you don't need to create new one, just inject your DbContext and use your DbSets
alright thanks alot for your help 🙂
$close
Use the /close command to mark a forum thread as answered