What's the best practice to log any appearing errors caused by Entity Framework?
Currently I'm using log4net, but I think this is independent to the logging framework.
Regarding an example API:
public class TestController : ApiController
{
[HttpGet]
public IEnumerable<Test> GetTests()
{
using(var context = new DatabaseContext())
{
return context.Tests.Where(w=>w.Enabled).ToList();
}
}
}
For now, I would have to stick my method body in a try/catch (and I'd have to stick all method bodies of all controllers in try/catch blocks)
try
{
using (var context = new DatabaseContext())
{
return context.Tests.Where(w=>w.Enabled).ToList();
}
}
catch(Exception e)
{
// TODO: handle also those ValidationErrors, thrown by Entity Framework
// so here we get a lot more code
_logger.Error(e);
}
But I don't want to put any method body of my API in a try/catch block.
Is there a possibility like adding an OnException in my DatabaseContext class, where I always can log any exception thrown by Entity Framework?
You can look into the following:
Global Error Handling in ASP.NET Web API 2
Exception Filters
To take things even further, if you want to get detailed information about what is going on with the underlying commands, you can implement an Interceptor as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With