debugcsharpMinor
Handling exceptions for providing log information while debugging
Viewed 0 times
handlingexceptionswhiledebugginglogprovidingforinformation
Problem
I am catching exceptions to provide better information for the logs to make debugging easier in production. Does this code follow best practices, since I'm not really handling the error but just logging extra information? I was also considering creating a custom
RazorException, and throwing that instead. What do you think?public string ParseFile(string templatePath, object model = null)
{
//some code removed for clarity
try
{
ITemplate template = _templateService.Resolve(templatePath, model);
ExecuteContext context = new ExecuteContext();
content = template.Run(context);
}
catch (TemplateCompilationException tcex) {
_logger.Fatal("Razor parse failed: check for syntax error", tcex);
throw;
}
catch (InvalidOperationException ex) {
_logger.Fatal("Razor parse failed: trying to compile layout on its own", ex);
throw;
}
catch (Exception ex) {
_logger.Fatal("Razor parse failed", ex);
throw;
}
return content;
}Solution
Exceptions have
Not to mention, that the guy debugging your code will likely prefer to know what went wrong straight away, without the need to look for log messages in your code or in log files.
Message property, which you should use, if you want to tell someone what went wrong in human language. You can then use String.Format("Razor parse failed: {0}", ex.Message) for all your exceptions. This will allow you, for example, to throw multiple InvalidOperationExceptions in the future without worrying about how you are going to log those. Not to mention, that the guy debugging your code will likely prefer to know what went wrong straight away, without the need to look for log messages in your code or in log files.
Context
StackExchange Code Review Q#58732, answer score: 7
Revisions (0)
No revisions yet.