使用预处理器C++定义常见错误消息
Defining common error messages with preprocessor C++
假设我有多个地方调用函数int foo(x, y)
。根据返回代码,我决定是否打印错误消息。所以代码看起来类似于这样:
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__;
...
}
我遇到的问题是"Error occurred"
在许多地方重复,到处都是一样的。我想知道使用 #define
定义常见错误消息并重用它们是否是一种好习惯。所以代码是这样的:
#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;
...
}
显而易见的事情就是将错误消息放在foo
本身中。 如果你做不到,那就把它包装起来:
bool fooWithLogging(int x, iny y)
{
auto result = foo(x,y);
if (result)
{
std::cerr << "Error occurred with values" << x << "," << y << std::endl;
}
}
在代码中调用包装器:
void func1()
{
...
fooWithLogging(x,y);
...
}
void func2()
{
...
fooWithLogging(x,y);
...
}
奖励:使日志记录动态化:
#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;
}
}
现在,有了刚刚在评论中提到的文件和行要求:
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__)
然后在代码中:
void func1()
{
...
FooWithLogging(x,y);
...
}
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- QT在错误的班级中寻找空位
- vector.resize()中的分配错误
- 代码在main()中运行,但在函数中出现错误
- 释放错误后堆使用
- (C++)分析树以计算返回错误值的简单算术表达式
- Project Euler问题4的错误解决方案
- 我的字符计数代码计算错误.为什么
- 最长的常见子字错误结果
- 使用预处理器C++定义常见错误消息
- 编译基于 sCrypt 的加密货币 QT 客户端时,抛出常见错误
- 源文件编译器错误 - 常见问题
- 常见日志文件系统 API 的 RegisterManageableLogClient() 和"access is denied"错误
- 在多线程c++应用程序中,调试分段错误的一些常见方法是什么
- 在epoll边缘触发模式下,哪些常见的编程错误会导致CLOSE_WAIT卡住?
- C++返回字符串中最常见字符的函数中的错误.多字节字符