Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework log any errors

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?

like image 340
Matthias Burger Avatar asked Dec 05 '25 10:12

Matthias Burger


1 Answers

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.

like image 190
William Xifaras Avatar answered Dec 07 '25 00:12

William Xifaras