In my current project I see a lot of this type of code:
public User GetUserByName(string userName)
{
try
{
// Lots of code here to check if the user is in the cache,
// get it from the DB if not, set properties on it, etc...
}
catch (Exception ex)
{
throw new Exception("Exception getting user by name, username: " + userName, ex);
}
}
I appreciate the intent here, having the local variables is really useful for debugging, but putting a try/catch around every method seems like far too much work, and it really doesn't help the readability. For now I'm ignoring the fact that we're throwing a System.Exception, naturally a more specific type would be better but it's not the focus of my question. Also it probably goes without saying that this gets copied and pasted around heavily without any modifications to the exception message...
So my question is: how do you capture this kind of contextual information (e.g. username in the above example) for debugging? Let's assume for the purposes of the question that the method is otherwise well-written and any specific exception checking is taken care of, and all I want is to add context to any exception that can't be handled here and needs to bubble up to the top-level handlers.
My first thoughts:
Lean on the logging framework to trace out each method call with it's parameters, which again is really boilerplate-y and is far more logging than appropriate for production.
Bring in some AOP and intercept every method (or a limited subset), checking for an exception on the return and either logging the parameters or adding them to the thrown exception.
Any other opinions welcome!