开发者

Search for specific try/catch block using RegEx

开发者_如何学Go

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜