简体   繁体   English

使用预处理器 C++ 定义常见错误消息

[英]Defining common error messages with preprocessor C++

Let's say I have multiple places where I call function int foo(x, y) .假设我有多个地方调用函数int foo(x, y) Based on the return code, I decide whether to print an error message or not.根据返回码,我决定是否打印错误消息。 So the code looks similar to this:所以代码看起来类似于:

  void func1()
    {
        ...
        if(foo(x,y))
            std::cerr << "Error occurred with values" << x << "," << y << __LINE__;
        ...
    }

    void func2()
    {
        ...
        if(foo(x,y))
            std::cerr << "Error occurred with values" << x << "," << y << __LINE__;
        ...
    }

The problem that I have is that "Error occurred" is repeating in many places and is the same everywhere.我遇到的问题是"Error occurred"在很多地方重复出现并且到处都是一样的。 I was wondering if it's a good practice to define common error messages using #define and reuse them.我想知道使用#define定义常见错误消息#define用它们是否是一个好习惯。 So the code would like like this:所以代码是这样的:

  #define errMsg(x,y) \
    std::string("Error occurred with values " + to_string(x) + "," + to_string(y) + to_string(__LINE__))

  void func1()
    {
        ...
        if(foo(x,y))
            std::cerr << errMsg;
        ...
    }

    void func2()
    {
        ...
        if(foo(x,y))
            std::cerr << errMsg;
        ...
    }

The obvious thing to do is just to put the error message in foo itself.显而易见的事情就是将错误消息放在foo本身中。 If you can't do that, then just wrap it:如果你不能这样做,那就把它包装起来:

bool fooWithLogging(int x, iny y)
{
    auto result = foo(x,y);
    if (result)
    {
        std::cerr << "Error occurred with values" << x << "," << y << std::endl;
    }
}

The call the wrapper in your code:在您的代码中调用包装器:

void func1()
{
    ...
    fooWithLogging(x,y);
    ...
}

void func2()
{
    ...
    fooWithLogging(x,y);
    ...
}

Bonus: make the logging dynamic:奖励:使日志记录动态:

#ifdef DEBUG
bool g_isFooLoggingEnabled = true;
#else
bool g_isFooLoggingEnabled = false;
#endif

bool fooWithLogging(int x, iny y)
{
    auto result = foo(x,y);
    if (result && g_isFooLoggingEnabled)
    {
        std::cerr << "Error occurred with values" << x << "," << y << std::endl;
    }
}

And now with your FILE and LINE requirement that just alluded to in the comments:现在,您在评论中提到的 FILE 和 LINE 要求:

bool _fooWithLogging(int x, iny y, const std::string& filename, int line)
{
    auto result = foo(x,y);
    if (result && g_isFooLoggingEnabled)
    {
        std::cerr << "Error occurred in file" << filename << " on line " << line << " with values" << x << "," << y << std::endl;
    }
}

#define FooWithLogging(x, y) _fooWithLogging(x, y, __FILE__, __LINE__)

Then in code:然后在代码中:

void func1()
{
    ...
    FooWithLogging(x,y);
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM