3

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?

3
  • 1
    check 3rd type of exception handling in dotnetcurry.com/aspnet-mvc/1068/aspnet-mvc-exception-handling Commented Jan 12, 2017 at 9:41
  • @PranavPatel haha, this page really looks like curry... you mean that HandleErrorAttribute? Commented Jan 12, 2017 at 9:43
  • 1
    @MatthiasBurger Yes you add that to the global filters. Commented Jan 12, 2017 at 23:10

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

the combination of exception filter and the interceptor-implementation fits perfectly me needs. Thx!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.