Search for specific try/catch block using RegEx
Is was wondering how to search for try/catch block that does't have log.Error(ex) inside its catch block. By search, I mean using Visual Studio built in regex search.
Regex would find block like this:
try
{
CallSomeExceptionalFunction();
}
catch(Exception ex)
{
CallSomething();
// missing error handling
}
This block should be skipped by regex since it contains log.Error:
try
{
CallSomeExceptionalFunction();
}
catch(Exception ex)
{
log.Error(ex);
}
You cannot parse programming languages based on a context-free grammar with a regular expression.
Just imagine that there was a try-catch block inside your catch block, and another try-catch block in its catch block, and only one of them has the log.Error in it.
Assuming that you want to do it in code I wouldn't worry about a Regex, I'd just search for the word catch
, then count the number of starting braces after that {
and subtracting any ending braces }
from that count, stopping when I found a line containing log.Error
and if the line isn't found before the count reaches zero, then you've got an instance where the log is missing.
精彩评论